我在STAX java中需要指导我有xml文件,我需要在满足前一个父节点book id属性值之前获取内部元素值。例如。
<books>
<book id = "1">
<chap num ="1"> This First Title </chap>
<chap num ="2"> This second of first book </chap>
</book>
<book id = "2">
<chap num ="1"> This First Title of second book </chap>
<chap num = "2"> This Second of second book </chap>
</book>
</books>
我需要基于书籍属性id的比较,来自“chap”元素的属性值。
只是提示会引导我。
答案 0 :(得分:0)
你需要沿着这些方向做点什么
String xmlString = ...
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.parse(xmlString);
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
String xpathExp = "/books/book[@id=\"2\"]";
Node node = (Node) xpath.evaluate(xpathExp, doc, XPathConstants.NODE);
来自&#34;书&#34;你可以循环遍历子节点(&#34; chap&#34;节点)。或者,您可以通过以下方式直接访问子节点列表:
String xpathExp = "/books/book[@id=\"2\"]/chap";
NodeList chapNodeList = (NodeList) xpath.evaluate(xpathExp, doc, XPathConstants.NODESET);
然后,您可以从&#34; chap&#34;中检索属性值。节点。 (例如,node.getTextContent();
)
或者,如果您知道所需的章节,请将xpath表达式修改为更具体。