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")
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:
I wrapped your xml in <brochures></brochures> to make it a tree instead of a forest (ie single root node);
If you want to read from a file instead of a string, use lxml.etree.parse() instead of lxml.etree.fromstring()
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]
Yes, it is very possible. Two libraries to help you with this is ElementTree and lxml. Take a look at them.
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
For short xml file like this, I suggest you minidom.