簡體   English   中英

使用ElementTree庫解析XML

[英]Parse XML with using ElementTree library

我正在嘗試解析xml數據以使用python 3中的ElementTree庫打印其內容,但是當我打印lst時,它返回了一個空列表。

錯誤:返回列表的空數組。

我的嘗試:

import xml.etree.ElementTree as ET
data = '''
    <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>
    </data>'''

tree = ET.fromstring(data)
lst = tree.findall('data/country')
print(lst)
#for item in lst:
#    print('Country: ', item.get('name'))

提前致謝。

樹已經引用了根項<data>因此它不應出現在path語句中。 只需找到“國家”。

import xml.etree.ElementTree as ET
data = '''
    <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>
    </data>'''

tree = ET.fromstring(data)
lst = tree.findall('data/country')
print(lst)

# check position in tree
print(tree.tag)
print(tree.findall('country'))

暫無
暫無

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

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