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