XPath - 根据相同条件从不同路径检索多个值

时间:2013-01-25 01:29:55

标签: xml xpath xml-parsing

这是我的XML

<root>
   <entry id="1">
      <value name="ID">11</value>
      <value name="ENABLE">0</value>
      <value name="NAME">USER1</value>
   </entry>
   <entry id="2">
      <value name="ID">11</value>
      <value name="ENABLE">0</value>
      <value name="NAME">USER2</value>
   </entry>
   <entry id="3">
      <value name="ID">12</value>
      <value name="ENABLE">0</value>
      <value name="NAME">USER1</value>
   </entry>
</root>

我需要一个XPath查询来检索id 11 的所有名称。

我试过了:

String xpath = "/root/entry/value[@name=ID/text()='11']/value[@name='NAME']";
String xpath = "/root/entry/value[@name=ID/text()='11']/NAME";

有人能告诉我查询中有什么问题吗?

修改

预期产出:

USER1
USER2

这两个都有ID = 11

5 个答案:

答案 0 :(得分:3)

/root/entry[value[@name="ID" and .=11]]/value[@name="NAME"]

/root/entry/value[@name="ID" and .=11]/../value[@name="NAME"]

/descendant::entry[value=11 and value/@name="ID"]/value[@name="NAME"]

//value[.=11]/@name[.="ID"]/ancestor::entry/value[@name="NAME"]

或许多其他变体

答案 1 :(得分:1)

使用

/*/*[*[@name='ID'] = 11]/*[@name='NAME']

基于XSLT的验证

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>

 <xsl:template match="/">
  <xsl:copy-of select="/*/*[*[@name='ID'] = 11]/*[@name='NAME']"/>
 </xsl:template>
</xsl:stylesheet>

将此转换应用于提供的XML文档

<root>
    <entry id="1">
        <value name="ID">11</value>
        <value name="ENABLE">0</value>
        <value name="NAME">USER1</value>
    </entry>
    <entry id="2">
        <value name="ID">11</value>
        <value name="ENABLE">0</value>
        <value name="NAME">USER2</value>
    </entry>
    <entry id="3">
        <value name="ID">12</value>
        <value name="ENABLE">0</value>
        <value name="NAME">USER1</value>
    </entry>
</root>

评估XPath表达式并将此评估结果(所有选定节点)复制到输出

<value name="NAME">USER1</value>
<value name="NAME">USER2</value>

答案 2 :(得分:0)

试试这个,

字符串xpath =“/ root / entry [value [@ name ='ID'和text()='11']] / value [@ name =”NAME“]”;

答案 3 :(得分:0)

这将是正确的路径:

/root/entry[value[@name = 'ID'] = 11]/value[@name = 'NAME']

要检索节点列表,您需要使用带有returnType参数的xPath.evaluate()版本:

InputSource document = new InputSource(new FileInputStream("user1.xml"));
String xpath = "/root/entry[value[@name = 'ID'] = 11]/value[@name = 'NAME']";
NodeSet result = (NodeSet)xPath.evaluate(xpath, document, XPathConstants.NODESET); 
for(int index = 0; index < result.getLength(); index ++) {      
    Node node = result.item(index);
    String name = node.getNodeValue();
}

答案 4 :(得分:0)

使用:

//entry[value[@name = 'ID'] = 11]/value[@name = 'NAME']