我有以下xml.I需要从上面的xml中获取bcc,cc,main,subject的值。
我该如何解析这个?
<?xml version="1.0" encoding="UTF-8"?>
<abc>
<pqr ref1="8340403366" ref2="0000000228754072" ref3="3200051014">
</pqr>
<errors>
<subject>Error is there</subject>
<mailto bcc="priyanka.chaddha@gmail.com" cc="richard.gayle@gmail.com"main="richard.gayle@gmail.com"/>
<text mnofield="000020"/>
</errors>
</abc>
答案 0 :(得分:0)
如果你试图解析一个xml文件,这样可以帮助你:
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(file);
XPath xPath = XPathFactory.newInstance().newXPath();
String expression = "//pqr/@ref1"; // This line defines the element or attribute that you want to retrieve
Node node = (Node) xPath.compile(expression).evaluate(doc, XPathConstants.NODE);
String nodeValue = node.getTextContent();
如果您的xml文件具有重复的元素和属性,您可能希望将值存储在NodeList中。为此您可以使用:
NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(doc, XPathConstants.NODESET);
您应该查看以下链接:
http://www.roseindia.net/tutorials/xPath/index.shtml
https://msdn.microsoft.com/en-us/library/ms256086(v=vs.110).aspx