[英]Problem traversing XML tree with Python xml.etree.ElementTree
[英]Searching attributes of an XML's element tree with xml.etree.ElementTree
我將使用從Python的ElementTree文檔的例子在這里 :
<?xml version="1.0"?>
<data>
<country name="Liechtenstein">
<rank>1</rank>
<year>2008</year>
<gdppc>141100</gdppc>
<neighbor name="Austria" direction="E"/>
<neighbor name="Switzerland" direction="W"/>
</country>
<country name="Singapore">
<rank>4</rank>
<year>2011</year>
<gdppc>59900</gdppc>
<neighbor name="Malaysia" direction="N"/>
</country>
<country name="Panama">
<rank>68</rank>
<year>2011</year>
<gdppc>13600</gdppc>
<neighbor name="Costa Rica" direction="W"/>
<neighbor name="Colombia" direction="E"/>
</country>
</data>
有沒有辦法搜索屬性並返回屬性匹配的元素? 在上面的例子中,我想搜索屬性名稱為Singapore的元素。 findall()
函數只按標簽名稱搜索,即“country”,“rank”等。我知道我可以遍歷所有國家標簽,看看他們的名字屬性是否與新加坡相匹配,但我想知道是否有更快的方法使用我缺少的內置函數。
使用XPath表達式(如正則表達式,但對於XML)
類似於上面的例子:
# Nodes with name='Singapore' that have a 'year' child
root.findall(".//year/..[@name='Singapore']")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.