Data from XML to Python list

僤鯓⒐⒋嵵緔 提交于 2019-12-04 14:53:48

问题


Is it possible to store data from an XML file to a list in python. For example I have an XML file with the following content:

<brochure>
<onlinePath>http://EEE</onlinePath>
<downloadPath>http://YYY</downloadPath>
<Name>ABC</Name>
<AAA>
    <P>JPG</P>
        <Q>JPG</Q>
</AAA>
</brochure>
<brochure>
<onlinePath>http://EKK</onlinePath>
<downloadPath>http://XXX</downloadPath>
<Name>DEF</Name>
<AAA>
    <P>JPG</P>
        <Q>JPG</Q>
</AAA>
</brochure>

Is it possible to store into a python list like:

onlinePath = ("http://EEE", "http://EKK")
Name = ("ABC", "DEF")

回答1:


import lxml

xml = """
<brochures>
    <brochure>
        <onlinePath>http://EEE</onlinePath>
        <downloadPath>http://YYY</downloadPath>
        <Name>ABC</Name>
        <AAA>
            <P>JPG</P>
            <Q>JPG</Q>
        </AAA>
    </brochure>
    <brochure>
        <onlinePath>http://EKK</onlinePath>
        <downloadPath>http://XXX</downloadPath>
        <Name>DEF</Name>
        <AAA>
            <P>JPG</P>
            <Q>JPG</Q>
        </AAA>
    </brochure>
</brochures>
"""

root = lxml.etree.fromstring(xml)
mylist = root.xpath('//brochure/onlinePath/text()')

results in

['http://EEE', 'http://EKK']

Notes:

  1. I wrapped your xml in <brochures></brochures> to make it a tree instead of a forest (ie single root node);

  2. If you want to read from a file instead of a string, use lxml.etree.parse() instead of lxml.etree.fromstring()




回答2:


Hugh's solution is fine. Here is a variation that uses ElementTree (tested with Python 2.6):

from xml.etree import ElementTree

tree = ElementTree.parse("yourfile.xml")   
olp = tree.findall("//onlinePath")
mylist = [t.text for t in olp]



回答3:


Yes, it is very possible. Two libraries to help you with this is ElementTree and lxml. Take a look at them.




回答4:


i don't think it can store it in lists bt it can store it in dictionaries since they have key:values using expat for xml

but can check the entries here




回答5:


For short xml file like this, I suggest you minidom.




回答6:


Check out BeautifulSoup



来源:https://stackoverflow.com/questions/4525735/data-from-xml-to-python-list

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!