【问题标题】:Is there a way to store xml sub tags in a list in python?有没有办法将 xml 子标签存储在 python 的列表中?
【发布时间】:2019-10-09 23:59:57
【问题描述】:

我正在尝试使用 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 标记的详细信息。

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

不幸的是,当我尝试遍历 XML 文件时,它给了我一个包含确切内容的对象。 .attrib 为我返回一个字典。

【问题讨论】:

  • 您的示例不是有效的 XML。
  • 是什么阻止了您根据“iter”为您提供的内容构建列表?

标签: python python-3.x xml.etree


【解决方案1】:

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

这是假设您通过删除重复的 &lt;State&gt; 标记并使用结束 &lt;/Data&gt; 标记来修复 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')])])])]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多