【问题标题】:Generating nested lists from XML doc从 XML 文档生成嵌套列表
【发布时间】:2023-04-10 22:39:02
【问题描述】:

在 python 中工作,我的目标是解析我制作的 XML 文档并创建一个嵌套列表列表,以便以后访问它们并解析提要。 XML 文档类似于以下 sn-p:

<?xml version="1.0'>
<sources>
    <!--Source List by Institution-->
    <sourceList source="cbc">
        <f>http://rss.cbc.ca/lineup/topstories.xml</f>
    </sourceList>
    <sourceList source="bbc">
        <f>http://feeds.bbci.co.uk/news/rss.xml</f>
        <f>http://feeds.bbci.co.uk/news/world/rss.xml</f>
        <f>http://feeds.bbci.co.uk/news/uk/rss.xml</f>
    </sourceList>
    <sourceList source="reuters">
        <f>http://feeds.reuters.com/reuters/topNews</f>
        <f>http://feeds.reuters.com/news/artsculture</f>
    </sourceList>
</sources>

我想要类似嵌套列表的东西,其中最里面的列表是&lt;f&gt;&lt;/f&gt; 标记之间的内容,而上面的列表将使用源名称创建。 source="reuters" 是路透社。从 XML 文档中检索信息不是问题,我正在使用 elementtree 进行此操作,并使用 node.get('source') 等进行循环检索。问题是我无法生成具有所需名称和所需不同长度的列表从不同的来源。我尝试过追加,但不确定如何将检索到的名称追加到列表中。字典会更好吗?在这种情况下,最佳做法是什么?我怎样才能使这项工作?如果需要更多信息,请发表评论,我一定会添加它。

【问题讨论】:

  • 您想如何使用这些列表?如果通过键查找源和提要,您将需要嵌套字典。如果按键查找源,然后遍历源的所有提要,您将需要一个列表字典。等等。

标签: python xml list nested


【解决方案1】:

根据您的描述,具有根据源名称的键和根据提要列表的值的字典可能会起作用。

这是构建这种野兽的一种方法:

from lxml import etree
from pprint import pprint

news_sources = {
    source.attrib['source'] : [feed.text for feed in source.xpath('./f')]
    for source in etree.parse('x.xml').xpath('/sources/sourceList')}

pprint(news_sources)

另一个示例,没有lxmlxpath

import xml.etree.ElementTree as ET
from pprint import pprint

news_sources = {
    source.attrib['source'] : [feed.text for feed in source]
    for source in ET.parse('x.xml').getroot()}

pprint(news_sources)

最后,如果你对列表推导过敏:

import xml.etree.ElementTree as ET
from pprint import pprint

xml = ET.parse('x.xml')
root = xml.getroot()
news_sources = {}
for sourceList in root:
    sourceListName = sourceList.attrib['source']
    news_sources[sourceListName] = []
    for feed in sourceList:
       feedName = feed.text
       news_sources[sourceListName].append(feedName)

pprint(news_sources)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-22
    • 2020-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-09
    相关资源
    最近更新 更多