如何使用 XPATH 解析 XML [英] How to parse XML using XPATH

查看:29
本文介绍了如何使用 XPATH 解析 XML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to scan following XML and fetch value of id based on condition name=task2 and value=efg.

<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>    

我可以使用

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

但不是使用以下代码的 id 的值

But not the value of id using following code

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

如何获取正确结果的值ABC-123"和RST-567"?

How to get values "ABC-123" and "RST-567" which would be the correct result?

参考以下博客和 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

Referring following blog and w3c links
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

推荐答案

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

You can nest predicates (expression in []) to achieve that, for example :

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

这篇关于如何使用 XPATH 解析 XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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