java字元串xml
❶ java如何把String轉換成xml
導入dom4j這個包,然後使用這個包裡面的東西 進行解析與封裝
❷ java json字元串轉換xml字元串
java json字元串轉成 xml可以用XStream 這個攔好渣jar來轉換, 首先要把json轉襪納成java對象, 再轉成xml字元簡悄串.
❸ java分割xml類型的字元串
你可以搜索下dom4j解析xml 網上很多,例如:
public class TestDom4j {
20
21 public void readStringXml(String xml) {
22 Document doc = null;
23 try {
24
25 // 讀取並解析XML文檔
26 // SAXReader就是一個管道,用一個流的方式,爛孝把xml文件讀出來
27 //
28 // SAXReader reader = new SAXReader(); //User.hbm.xml表示你要解析的xml文檔
29 // Document document = reader.read(new File("User.hbm.xml"));
30 // 下面的是通過解析xml字元串的
31 doc = DocumentHelper.parseText(xml); // 將字元串轉為XML
32
33 Element rootElt = doc.getRootElement(); // 獲取根節點
34 System.out.println("根節點:" + rootElt.getName()); // 拿到根節點的名稱
35
36 Iterator iter = rootElt.elementIterator("head"); // 獲森塌取根節點下的子節點head
37
38 // 遍歷head節點
39 while (iter.hasNext()) {
40
41 Element recordEle = (Element) iter.next();
42 String title = recordEle.elementTextTrim("title"); // 拿到head節點下的子節點title值
43 System.out.println("title:" + title);
44
45 Iterator iters = recordEle.elementIterator("script"); // 獲取子節點head下的子節點script
46
47 // 遍歷Header節點下的Response節點
48 while (iters.hasNext()) {
49
50 Element itemEle = (Element) iters.next();
51
52 String username = itemEle.elementTextTrim("username"); //此歷圓 拿到head下的子節點script下的位元組點username的值
53 String password = itemEle.elementTextTrim("password");
54
55 System.out.println("username:" + username);
56 System.out.println("password:" + password);
57 }
58 }
59 Iterator iterss = rootElt.elementIterator("body"); ///獲取根節點下的子節點body
60 // 遍歷body節點
61 while (iterss.hasNext()) {
62
63 Element recordEless = (Element) iterss.next();
64 String result = recordEless.elementTextTrim("result"); // 拿到body節點下的子節點result值
65 System.out.println("result:" + result);
66
67 Iterator itersElIterator = recordEless.elementIterator("form"); // 獲取子節點body下的子節點form
68 // 遍歷Header節點下的Response節點
69 while (itersElIterator.hasNext()) {
70
71 Element itemEle = (Element) itersElIterator.next();
72
73 String banlce = itemEle.elementTextTrim("banlce"); // 拿到body下的子節點form下的位元組點banlce的值
74 String subID = itemEle.elementTextTrim("subID");
75
76 System.out.println("banlce:" + banlce);
77 System.out.println("subID:" + subID);
78 }
79 }
80 } catch (DocumentException e) {
81 e.printStackTrace();
82
83 } catch (Exception e) {
84 e.printStackTrace();
85
86 }
87 }
❹ java如何解析xml格式的字元串
使用dom4j,在網路下搜一個dom4j包,然後在網上找個例子看dom4j操作xml的使用方法,很簡單的。
❺ JAVA 如何獲取並替換XML格式的字元串
xml文件:
<?xml version="1.0" encoding="UTF-8"改銷?>
<transaction>
<body>
<request>
<tranTyp>批量業務現存</tranTyp>
<acctNm>0085213560</acctNm>
<acctNo>6225885517843413</acctNo>
<avlBal>201958.65</avlBal>
<acctTyp>0</acctTyp>
<tranTime>20170801101030</tranTime>
<currencyTyp>CNY</currencyTyp>
<tranDesc></tranDesc>
<bal>201958.65</bal>
<tranAmt>100000.00</tranAmt>
</request>
</body>
<header>
<msg>
<sndTm>101019</sndTm>
<msgCd>WCS0000200</msgCd>
<seqNb>632376531000009</seqNb>
<sndMbrCd>5200</sndMbrCd>
<rcvMbrCd>0000</rcvMbrCd>
<sndDt>20170821</sndDt>
<sndAppCd>CBS</sndAppCd>
<rcvAppCd>WCS</rcvAppCd>
<callTyp>SYN</callTyp>
</msg>
<ver>1.0</ver>
<pnt>
<sndTm>101216</sndTm>
<sndMbrCd>0000</sndMbrCd>
<rcvMbrCd>0000</rcvMbrCd>
<sndDt>20170809</sndDt>
<sndAppCd>ESB</sndAppCd>
<rcvAppCd>WCS</rcvAppCd>
</pnt>
</header>
</transaction>
2. java實現實例:
public class Test {
/**
*
* @param document
* Document對象(讀xml生成的)
* @return String字元串
* @throws Throwable
*/
public String xmlToString(Document document) throws Throwable {
TransformerFactory ft = TransformerFactory.newInstance();
Transformer ff = ft.newTransformer();
ff.setOutputProperty("encoding", "GB2312");
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ff.transform(new DOMSource(document), new StreamResult(bos));
return bos.toString();
}
/**
*
* @param xml形狀的str串
* @return Document 對象
*/
public Document StringTOXml(String str) {
StringBuilder sXML = new StringBuilder();
sXML.append(str);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
Document doc = null;
try {
InputStream is = new ByteArrayInputStream(sXML.toString().getBytes("utf-8"));
doc = dbf.newDocumentBuilder().parse(is);
is.close();
} catch (Exception e) {
e.printStackTrace();
}
return doc;
}
/**
*
* @param document
* @return 某個節點的值 前提是核謹游晌宏需要知道xml格式,知道需要取的節點相對根節點所在位置
*/
public String getNodeValue(Document document, String nodePaht) {
XPathFactory xpfactory = XPathFactory.newInstance();
XPath path = xpfactory.newXPath();
String servInitrBrch = "";
try {
servInitrBrch = path.evaluate(nodePaht, document);
} catch (XPathExpressionException e) {
e.printStackTrace();
}
return servInitrBrch;
}
/**
*
* @param document
* @param nodePath
* 需要修改的節點相對根節點所在位置
* @param vodeValue
* 替換的值
*/
public void setNodeValue(Document document, String nodePath, String vodeValue) {
XPathFactory xpfactory = XPathFactory.newInstance();
XPath path = xpfactory.newXPath();
Node node = null;
;
try {
node = (Node) path.evaluate(nodePath, document, XPathConstants.NODE);
} catch (XPathExpressionException e) {
e.printStackTrace();
}
node.setTextContent(vodeValue);
}
3. 測試
public static void main(String[] args) throws Throwable {
// 讀取xml文件,生成document對象
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
// 文件的位置在工作空間的根目錄(位置隨意,只要寫對就ok)
Document document = builder.parse(new File("a.xml"));
Test t = new Test();
// XML————》String
String str = t.xmlToString(document);
System.out.println("str:" + str);
// String ————》XML
Document doc = t.StringTOXml(str);
String nodePath = "/transaction/header/msg/sndMbrCd";
// getNodeValue
String nodeValue = t.getNodeValue(doc, nodePath);
System.out.println("修改前nodeValue:" + nodeValue);
// setNodeValue
t.setNodeValue(doc, nodePath, nodeValue + "hello");
System.out.println("修改後nodeValue:" + t.getNodeValue(doc, nodePath));
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
測試結果:
str:<?xml version="1.0" encoding="UTF-8" standalone="no"?><transaction>
<body>
<request>
<tranTyp>批量業務現存</tranTyp>
<acctNm>0085213560</acctNm>
<acctNo>6225885517843413</acctNo>
<avlBal>201958.65</avlBal>
<acctTyp>0</acctTyp>
<tranTime>20170801101030</tranTime>
<currencyTyp>CNY</currencyTyp>
<tranDesc/>
<bal>201958.65</bal>
<tranAmt>100000.00</tranAmt>
</request>
</body>
<header>
<msg>
<sndTm>101019</sndTm>
<msgCd>WCS0000200</msgCd>
<seqNb>632376531000009</seqNb>
<sndMbrCd>5200</sndMbrCd>
<rcvMbrCd>0000</rcvMbrCd>
<sndDt>20170821</sndDt>
<sndAppCd>CBS</sndAppCd>
<rcvAppCd>WCS</rcvAppCd>
<callTyp>SYN</callTyp>
</msg>
<ver>1.0</ver>
<pnt>
<sndTm>101216</sndTm>
<sndMbrCd>0000</sndMbrCd>
<rcvMbrCd>0000</rcvMbrCd>
<sndDt>20170809</sndDt>
<sndAppCd>ESB</sndAppCd>
<rcvAppCd>WCS</rcvAppCd>
</pnt>
</header>
</transaction>結果顯示
修改前nodeValue:5200
修改後nodeValue:5200hello
❻ java 截取 xml(字元串)的子節點
你好,直瞎猛接indexOf <task> 跟 </task> 然後subString一下都沒問題.
或者正則磨唯橋表達式
<task>(.*?)</task>
如果是一個長期的工程,量比較大的山拍,考慮用dom4j來做吧.
http://xhy0422.iteye.com/blog/50235
對於已經是字元串的xml,可以
❼ 在Java中如何讀取XML字元串的元素值
java讀取xml節點元素,主要使用java提供的解析xml的工具類SAXParserFactory,如下代碼:
package xml.xmlreader;import java.io.File;import java.net.URL;import java.util.Properties;import javax.xml.parsers.SAXParser;import javax.xml.parsers.SAXParserFactory;public class CFGParser {//解析xml文件的工具類 private Properties props; public Properties getProps() { return props; } public void setProps(Properties props) { this.props = props; } public void parse(String filename) throws Exception { CFGHandler handler = new CFGHandler(); SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(false); factory.setValidating(false); SAXParser parser = factory.newSAXParser(); URL confURL = super.getClass().getClassLoader().getResource(filename); if (confURL == null) { System.out.println("Can't find configration file."); return; } try { parser.parse(confURL.toString(), handler); this.props = handler.getProps(); } finally { factory = null; parser = null; handler = null; } } public void parseFile(String filename) throws Exception { CFGHandler handler = new CFGHandler(); SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(false); factory.setValidating(false); SAXParser parser = factory.newSAXParser(); File f = new File(filename); if ((f == null) || (!f.exists())) return; try { parser.parse(f, handler); this.props = handler.getProps(); } finally { factory = null; parser = null; handler = null; } }}package xml.xmlreader;import java.util.Properties;import org.xml.sax.Attributes;import org.xml.sax.SAXException;import org.xml.sax.helpers.DefaultHandler; public class CFGHandler extends DefaultHandler{ private Properties props; private String currentSet; private String currentName; private StringBuffer currentValue = new StringBuffer(); public CFGHandler() { this.props = new Properties(); } public Properties getProps() { return this.props; } public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { this.currentValue.delete(0, this.currentValue.length()); this.currentName = qName; } public void characters(char[] ch, int start, int length) throws SAXException { this.currentValue.append(ch, start, length); } public void endElement(String uri, String localName, String qName) throws SAXException { this.props.put(qName.toLowerCase(), this.currentValue.toString().trim()); }}xml文件 <?xml version="1.0" encoding="UTF-8"?><xml-body> <refresh_userlist desc="用戶列表刷新間隔時間(秒)">6</refresh_userlist> <refresh_message desc="短消息刷新間隔時間(秒)">10</refresh_message> <morningbegin desc="上午上班時間">23:00</morningbegin> <morningend desc="上午下班時間">12:00</morningend> <afternoonbegin desc="下午上班時間">18:00</afternoonbegin></xml-body>jsp獲取各個節點的值:<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><html> <jsp:useBean id="cfgp" scope="page" class="xml.xmlreader.CFGParser"></jsp:useBean> <body> <% cfgp.parse("kaoqin.xml"); Properties pro = cfgp.getProps(); String stTime = pro.getProperty("morningbegin"); String edTime = pro.getProperty("morningend"); String afternoonbegin = pro.getProperty("afternoonbegin"); out.println(stTime+"\n"+edTime+"\n"+afternoonbegin); System.out.println(stTime+"\n"+edTime+"\n"+afternoonbegin); %> </body></html>
❽ java中怎樣取出XML格式字元串的節點屬性
這個可以用正則表達式來實現。。。
要看你xml具體內容,才能確定表達式該怎麼寫,我給你舉個簡單的例子
<a><b>hello</b><b>world</b></a>想提取出b標簽裡面的內容可以用下面的代碼實現
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
public static void main(String[] args){
String s = "<a><b>hello</b><b>world</b></a>";
Pattern pattern = Pattern.compile("<b>(.*?)</b>");
Matcher matcher = pattern.matcher(s);
while(matcher.find()){
System.out.println(matcher.group(1));
}
}
}
運行結果:
hello
world
如果很復雜的話。蔽喊。。可以用專門的解析XML的來解析。。。一般的自己寫個正則就可以解決了。。宏鬧野
希望能幫到你。。。仍有問題可以繼續追問或者直接HI我。彎晌。。
❾ 用Java怎麼把String類型的字元串轉化為XML格式輸出
java中將string轉換成xml文件,使用開源jar包 dom4j:
packagecom.webdesk.swing.powertable.util;
importjava.io.ByteArrayInputStream;
importjava.io.File;
importjava.io.FileWriter;
importjava.io.IOException;
importorg.dom4j.Document;
importorg.dom4j.DocumentException;
importorg.dom4j.io.OutputFormat;
importorg.dom4j.io.SAXReader;
importorg.dom4j.io.XMLWriter;
publicclassXmlUtil{
(StringfileName){
try{
SAXReadersaxReader=newSAXReader();//新建一個解析類
DocumenttempDocument=saxReader.read(XmlUtil.class.getClassLoader().getResourceAsStream(fileName));//讀入一個文件
returntempDocument.asXML();
}catch(DocumentExceptione){
e.printStackTrace();
}
returnnull;
}
//將字元串string類型轉換成xml文件
publicstaticvoidstrChangeXML(Stringstr)throwsIOException{
SAXReadersaxReader=newSAXReader();
Documentdocument;
try{
document=saxReader.read(newByteArrayInputStream(str.getBytes("UTF-8")));
OutputFormatformat=OutputFormat.createPrettyPrint();
/**將document中的內容寫入文件中*/
XMLWriterwriter=newXMLWriter(newFileWriter(newFile("src/com/webdesk/swing/powertable/digester/cctv.xml")),format);
writer.write(document);
writer.close();
}catch(DocumentExceptione){
e.printStackTrace();
}
}
}
❿ java如何解析傳來的xml字元串
一、使用最原始的javax.xml.parsers,標準的jdk api
// 字元串轉XML
String xmlStr = "......";
StringReader sr = new StringReader(xmlStr);
InputSource is = new InputSource(sr);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder=factory.newDocumentBuilder();
Document doc = builder.parse(is);
//XML轉字元串
TransformerFactory tf = TransformerFactory.newInstance();
Transformer t = tf.newTransformer();
t.setOutputProperty("encoding","GB23121"吵舉);//解決中文問題,試過用GBK不行
ByteArrayOutputStream bos = new ByteArrayOutputStream();
t.transform(new DOMSource(doc), new StreamResult(bos));
String xmlStr = bos.toString();
這里的XML DOCUMENT為org.w3c.dom.Document
二、使用dom4j後程序變得更簡單
// 字元串轉XML
String xmlStr = "......";
Document document = DocumentHelper.parseText(xmlStr);
// XML轉字元串做圓
Document document = ...;
String text = document.asXML();
這里的XML DOCUMENT為org.dom4j.Document
三、使用JDOM
JDOM的處理方式和第一種方法處理非常類似
//字元串轉XML
String xmlStr = ".....";
StringReader sr = new StringReader(xmlStr);
InputSource is = new InputSource(sr);
Document doc = (new SAXBuilder()).build(is);
//XML轉字元串
Format format = Format.getPrettyFormat();
format.setEncoding("gb2312"純碰塌);//設置xml文件的字元為gb2312,解決中文問題
XMLOutputter xmlout = new XMLOutputter(format);
ByteArrayOutputStream bo = new ByteArrayOutputStream();
xmlout.output(doc,bo);
String xmlStr = bo.toString();
這里的XML DOCUMENT為org.jdom.Document
四、JAVASCRIPT中的處理
//字元串轉XML
var xmlStr = ".....";
var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async=false;
xmlDoc.loadXML(xmlStr);
//可以處理這個xmlDoc了
var name = xmlDoc.selectSingleNode("/person/name");
alert(name.text);
//XML轉字元串
var xmlDoc = ......;
var xmlStr = xmlDoc.xml