如何使用XPATH解析XML

时间:2016-02-24 09:09:29

标签: android xml xpath

我想根据条件名称= task2和value = efg扫描以下XML并获取 id 的值。

<node1>
<node2>
    <node3>
        <id>ABC-123</id>
        <condition>
            <task name="task1" operation="and" value="abc" />
            <task name="task2" operation="and" value="efg" />
            <task name="task3" operation="and" value="hij" />
            <task name="task4" operation="or" value="klm" />
            <task name="task5" operation="and" value="nop" />
            <task name="task6" value="uvw" />
        </condition>
    </node3>
    <node3>
        <id>XYZ-987</id>
        <condition>
            <task name="task1" operation="and" value="cde" />
            <task name="task2" operation="and" value="abc" />
            <task name="task5" operation="and" value="nop" />
        </condition>
    </node3>
    <node3>
        <id>RST-567</id>
        <condition>
            <task name="task2" operation="and" value="efg" />
            <task name="task8" operation="and" value="jkl" />
            <task name="task9" operation="and" value="rst" />
            <task name="task10" value="xyz" />
        </condition>
    </node3>
</node2>
</node1>    

我可以使用

扫描并获得count = 2的结果
 String expression = "//node3/condition/task[@name='"+condition.getKey()+"' and @value='"+condition.getValue()+"']";

但不是使用以下代码

id 的值
String expression = "//node3/condition/task[@name='"+condition.getKey()+"' and @value='"+condition.getValue()+"']/node3/id";

如何获得价值&#34; ABC-123&#34;和&#34; RST-567&#34;哪个是正确的结果?

参考以下博客和w3c链接
https://xjaphx.wordpress.com/2011/12/24/android-xml-adventure-parsing-xml-using-xpath/
http://www.w3schools.com/xml/xml_xpath.asp
http://www.w3schools.com/xsl/xpath_operators.asp

2 个答案:

答案 0 :(得分:1)

您可以选择ID并筛选具有以下兄弟条件的任务:

/node1/node2/node3/id[following-sibling::condition/task[@name='task2' and @value='efg']]

要仅选择文本值,请使用

/node1/node2/node3/id/text()[../following-sibling::condition/task[@name='task2' and @value='efg']]

答案 1 :(得分:1)

您可以嵌套谓词([]中的表达式)来实现这一点,例如:

//node3[condition/task[@name='task2' and @value='efg']]/id