Generating nested lists from XML doc

后端 未结 1 1695
闹比i
闹比i 2021-01-28 17:36

Working in python, my goal is to parse through an XML doc I made and create a nested list of lists in order to access them later and parse the feeds. The XML doc resembles the f

相关标签:
1条回答
  • 2021-01-28 18:09

    From your description, a dictionary with keys according to the source name and values according to the feed lists might do the trick.

    Here is one way to construct such a beast:

    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)
    

    Another sample, without lxml or xpath:

    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)
    

    Finally, if you are allergic to list comprehensions:

    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)
    
    0 讨论(0)
提交回复
热议问题