从xml⽂件中获取某个标签的值
import java.io.ByteArrayInputStream;
import java.io.InputStream;
l.parsers.DocumentBuilderFactory;
l.xpath.XPath;
l.xpath.XPathExpressionException;
l.xpath.XPathFactory;
import org.w3c.dom.Document;
public class Test {
/**
*
* @param xml形状的str串
* @return Document 对象
*/
public Document StringTOXml(String str) {
StringBuilder sXML = new StringBuilder();
sXML.append(str);
DocumentBuilderFactory dbf = wInstance();
Document doc = null;
try {
InputStream is = new String().getBytes("utf-8"));
doc = wDocumentBuilder().parse(is);
is.close();
} catch (Exception e) {
e.printStackTrace();
}
return doc;
}
/**
*
* @param document
* @return 某个节点的值前提是需要知道xml格式,知道需要取的节点相对根节点所在位置
*/
public String getNodeValue(Document document, String nodePaht) {
XPathFactory xpfactory = wInstance();
XPath path = wXPath();
String servInitrBrch = "";
try {
servInitrBrch = path.evaluate(nodePaht, document);
} catch (XPathExpressionException e) {
e.printStackTrace();
}
return servInitrBrch;
}
public static void main(String[] args) throws Throwable {
String str = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n<data>\r\n <message>\r\n <status>0</status>\r\n <value>处理成功</value>\r\n </message>\r\n < Test t = new Test();
// String ————》XML
Document doc = t.StringTOXml(str);
String nodePath = "/data/policeCheckInfos/policeCheckInfo/compResult";
xml标签大全// getNodeValue
String nodeValue = t.getNodeValue(doc, nodePath);
System.out.println(nodeValue);
}
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论