<?xml version="1.0"?> <shop> <shoes> <brand>Nike</brand> <size>13</size> <colour>White</colour> <price>34.99</price> <additional name="abc">123</additional> <additional name="def">456</additional> <additional name="ghi">789</additional> <additional name="jkl">101</additional> </shoes> <trousers> <brand>Levi</brand> <size>36</size> <legSize>33</legSize> <colour>Stonewash</colour> <price>69.99</price> <additional name="mno">112</additional> <additional name="pqr">131</additional> <additional name="stu">415</additional> <additional name="vwx">161</additional> </trousers> </shop>
给定上面的xml文件,我将如何检索<additional>标签内所有标签的列表<shoes>?我想获取“名称”的所有值以及标签之间的数字值。像这样:
<additional>
<shoes>
abc, 123 def, 456 ghi, 789 jkl, 101
问题是我不知道会有多少个附加标签。可能没有,也可能有20。我需要某种方法来对它们全部进行计数,然后删除信息。
这是一个使用XPathJDK执行查询的示例。它假定变量xml包含您的XML文档。
XPath
xml
XPathFactory factory = XPathFactory.newInstance(); XPath xPath = factory.newXPath(); NodeList nodeList = (NodeList) xPath.evaluate("//shoes/additional", new InputSource(new StringReader(xml)), XPathConstants.NODESET); for (int i = 0; i < nodeList.getLength(); ++i) { String name = nodeList.item(i).getAttributes().getNamedItem("name").getNodeValue(); String text = nodeList.item(i).getTextContent(); System.out.println(name + ", " + text); }