XMLPath Query with "OR" 运算符



我得到了一个.xml文件,它有以下条目:

<country>
<province id="prov-cid-cia-Greece-3" country="GR">
<name>Attiki</name>
<area>3808</area>
<population>3522769</population>
<city id="cty-Greece-Athens" is_country_cap="yes" country="GR" province="prov-cid-cia-Greece-3">
<name>Athens</name>
<longitude>23.7167</longitude>
<latitude>37.9667</latitude>
<population year="81">885737</population>
<located_at watertype="sea" sea="sea-Mittelmeer"/>
</city>
</province>
</country>

然而,也有不以province为父节点而称为city的节点:

<country>
<city id="stadt-Shkoder-AL-AL" country="AL">
<name>Shkoder</name>
<longitude>19.2</longitude>
<latitude>42.2</latitude>
<population year="87">62000</population>
<located_at watertype="lake" lake="lake-Skutarisee"/>
</city>
</country>

没有进一步的解释,我想选择所有节点city,然而,在我当前的查询中,它只选择cities而不选择province作为父节点

query = f"//country/city[@is_country_cap = "yes" and ./located_at[@watertype]]/name/text()"

我怎么能包括/province/country在我的查询?我试过了:

query = f"//country/(city | ./province/city)[@is_country_cap = "yes" and ./located_at[@watertype]]/name/text()"

没有任何成功,我得到一个错误。

您可以匹配所有具有<country><province>父元素的<city>元素。然后,在第二个谓词中,像这样添加其他需求:

//city[parent::country or parent::province][@is_country_cap = 'yes' and located_at[@watertype]]/name

或者,接近你的语言

query = f"//city[parent::country or parent::province][@is_country_cap = "yes" and located_at[@watertype]]/name/text()"

也许这对你有些帮助。
您的错误是使用|运算符而不是关键字or。在XPath中,|操作符表示"合并节点集";而不是一个合乎逻辑的"or";

最新更新