簡體   English   中英

如何使用python獲取XML中的所有標簽?

[英]How to get all the tags in an XML using python?

我一直在研究Python Docs中從XML文件中獲取標記名稱的方法,但是我並不是很成功。 使用下面的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>

考慮使用元素樹的iterparse()並構建標記和文本對的嵌套列表。 if有條件, if邏輯將國家/地區項目組合在一起,並保留沒有文本的元素,則使用replace()清除換行符和iterparse()拾取的多個空白:

import xml.etree.ElementTree as et

data = []
for (ev, el) in et.iterparse(path):
    inner = []

    if el.tag == 'country':        
        for name, value in el.items():
            inner.append([el.tag+'-'+name, str(value).replace('\n','').replace(' ','')])
        for i in el:
            if str(i.text) != 'None':
                inner.append([i.tag, str(i.text).replace('\n','').replace(' ','')])

            for name, value in i.items():
                inner.append([i.tag+'-'+name, str(value).replace('\n','').replace(' ','')])
        data.append(inner)

print(data)
# [[['country-name', 'Liechtenstein'], ['rank', '1'], ['year', '2008'], ['gdppc', '141100'], 
#   ['neighbor-name', 'Austria'], ['neighbor-direction', 'E'], 
#   ['neighbor-name', 'Switzerland'], ['neighbor-direction', 'W']]
#  [['country-name', 'Singapore'], ['rank', '4'], ['year', '2011'], ['gdppc', '59900'], 
#   ['neighbor-name', 'Malaysia'], ['neighbor-direction', 'N']]
#  [['country-name', 'Panama'], ['rank', '68'], ['year', '2011'], ['gdppc', '13600'], 
#   ['neighbor-name', 'CostaRica'], ['neighbor-direction', 'W'], 
#   ['neighbor-name', 'Colombia'], ['neighbor-direction', 'E']]]

查看Python的內置XML功能,以遞歸方式遍歷文檔,並將所有標簽收集到一個集合中。

暫無
暫無

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

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