XPath - 如何获取具有相同名称的多个标签的列表 [英] XPath - how to get a list of multiple tags with the same name

查看:103
本文介绍了XPath - 如何获取具有相同名称的多个标签的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<?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 文件,我将如何检索 标签中所有 标签的列表?我想获取名称"的所有值以及标签之间的数值.像这样:

Given the above xml file, how would I retrieve a list of all <additional> tags within the <shoes> tag? I want to get all the values of 'name' along with the numeric value between the tags. Something like this:

abc, 123
def, 456
ghi, 789
jkl, 101

问题是我不知道会有多少额外的标签.可能没有,也可能有 20 个.我需要某种方法将它们全部计算出来,然后剔除信息.

The problem is I don't know how many additional tags there will be. There could be none and there could be 20. I need some way to count them all then strip out the information.

推荐答案

这是一个使用 JDK 中的 XPath 来执行查询的示例.它假定变量 xml 包含您的 XML 文档.

Here's an example that uses XPath from the JDK to execute a query. It assumes that the variable xml contains your XML document.

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);
}

这篇关于XPath - 如何获取具有相同名称的多个标签的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆