问题描述
我想要检索行/字段的 PName
,其中id = 2,pAddress = INDIA
I want to retrive PName
of the row/field whose id =2 and pAddress=INDIA
<?xml version="1.0"?>
<mysqldump >
<database name="MyDb">
<table name="DescriptionTable">
<row>
<field name="id">1</field>
<field name="pName">XYZ</field>
<field name="pAddress">INDIA</field>
<field name="pMobile">1234567897</field>
</row>
<row>
<field name="id">2</field>
<field name="pName">PQR</field>
<field name="pAddress">UK</field>
<field name="pMobile">755377</field>
</row>
<row>
<field name="id">3</field>
<field name="pName">ABC</field>
<field name="pAddress">USA</field>
<field name="pMobile">67856697</field>
</row>
</table>
</database>
</mysqldump>
String expression="/mysqldump/database[@name='MyDb']/table[@name='DescriptionTable']/row/field[@name='id' and ./text()]";
修改:
我想得到Pname whoese id为2而pAddress = INDIA
I would like to get Pname whoese id is 2 and pAddress=INDIA
String expression="/mysqldump/database[@name='MyDb']/table[@name='DescriptionTable']/row/field[@name='id' and .='2']and[@name='pAddress' and .='INDIA']/../field[@name='pName']/text()";
推荐答案
上述两个答案都可以通过移动方面得到改善将路径表达式转换为谓词,并使用嵌套的嵌套谓词。恕我直言,这使得XPath选择更具人性化。
Both of the above answers could be improved by moving aspects of the path expression into the predicates, and using nested nested predicates. IMHO this makes the XPath selection much more human readable.
首先我们找到行
,其中字段
其 @name eq id
和 text()=2
,从那里我们可以从行
中选择字段
,其中 @name eqpName
。
First we find the row
with the field
whose @name eq id
and text() = "2"
, from there we can simply select the field
from that row
whose the @name eq "pName"
.
/mysqldump/database[@name = "MyDb"]/table[@name = "DescriptionTable"]/row[field[@name eq "id"][text() = "2"]]/field[@name = "pName"]
另请注意明确使用 eq
和 =
,eq用于比较原子值,在本例中选择我们的属性, =
用于比较序列(因为可以想象text()可能会返回不止一个项目 - 虽然它不适用于您的示例XML)。
Also note the explicit use of eq
and =
, eq is used for comparing atomic values, in this instance the selection of our attributes, and =
is used for comparing sequences (as it is conceivable that text() may return more than one item - although it won't for your example XML).
这篇关于如何在Xpath中检查多个条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!