有没有办法将 xml 子标签存储在 python 的列表中?

Is there a way to store xml sub tags in a list in python?

我正在尝试使用 xml.etree 模块复制 BeautifulSoup 的 find_all 功能。 由于某些原因,我们不允许使用 bs4 包,因此 Beautiful soup 不在考虑之列。 有什么方法可以搜索特定标签,然后存储标签的每一行直到结束?

<data>
    <country name="Liechtenstein">
        <rank>1</rank>
        <year>2008</year>
        <gdppc>141100</gdppc>
        <neighbor name="Austria" direction="E"/>
        <neighbor name="Switzerland" direction="W"/>
    </country>
    <State name="Singapore"><State name="Singapore">
        <rank>4</rank>
        <year>2011</year>
        <gdppc>59900</gdppc>
        <neighbor name="Malaysia" direction="N"/>
    </State>

我需要类似的东西,在列表中获取状态标记的详细信息。

[<State name="Singapore">,<rank>4</rank>,.....,'</state>']

不幸的是,当我尝试遍历 XML 文件时,它给了我一个关于确切内容的对象。和 .attrib returns 对我来说是一个字典。

为什么不使用 xmlToDict 并遍历键?如果你只是想要一个普通的字典,你可以在 OrderedDict (like so) 上使用 json.dumps,但这里有一个例子假设你想保留顺序。

这是假设您通过删除重复的 <State> 标签并使用结束 </Data> 标签来修复 XML。

import xmltodict
from collections import OrderedDict

def listRecursive(d, key):
    for k, v in d.items():
        if isinstance(v, OrderedDict):
            for found in listRecursive(v, key):
                yield found
        if k == key:
            yield v

with open('PATH\TO\xmlFile.xml') as fd:
    xmlDict = xmltodict.parse(fd.read())

states = []
for result in listRecursive(xmlDict, 'State'):
    states.append(result)
states = states[0]

这是 pprint 的结果,假设您在新加坡之后添加另一个名为 NewState

的州
[OrderedDict([('@name', 'Singapore'),
              ('rank', '4'),
              ('year', '2011'),
              ('gdppc', '59900'),
              ('neighbor',
               OrderedDict([('@name', 'Malaysia'), ('@direction', 'N')]))]),
 OrderedDict([('@name', 'NewState'),
              ('rank', '7'),
              ('year', '2020'),
              ('gdppc', '99999'),
              ('neighbor',
               [OrderedDict([('@name', 'Unknown1'), ('@direction', 'S')]),
                OrderedDict([('@name', 'Unknown2'), ('@direction', 'N')])])])]