簡體   English   中英

如何通過使用python3在具有XML中特定屬性的節點中獲取值?

[英]How to get value in nodes with specific attribute in XML by using python3?

我是Python初學者。 現在,我正在處理XML和xml.etree.ElementTree
我正在處理下面的示例xml,

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

我想使用特定屬性在country標簽內獲取值。
例如,

我想獲得國家名稱=“新加坡”的排名,年份和gdppc

我嘗試過,但不知道該怎么做。
是否有可能做到這一點?

閱讀文檔中XPath示例 那已經說明了如何提取年份。

values = ['rank', 'year', 'gdppc']
for v in values:
    print(v, root.findall(".//*[@name='Singapore']/{}".format(v))[0].text)

產出

rank 4
year 2011
gdppc 59900

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM