<?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>
标记的列表?我想得到'name'的所有值以及标签之间的数值。像这样:
abc, 123
def, 456
ghi, 789
jkl, 101
问题是我不知道会有多少额外的标签。可能没有,可能有20个。我需要一些方法来计算它们然后删除信息。
答案 0 :(得分:0)
使用// shoes / additional,您将获得所有节点的列表,并可以使用Java迭代它。
答案 1 :(得分:0)
这是一个使用JDK中的XPath
来执行查询的示例。它假定变量xml
包含您的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);
}