Xml for Python data structure using lxml
How can I convert xml to Python data structure using lxml?
I searched high and low but found nothing.
Input example
<ApplicationPack>
<name>Mozilla Firefox</name>
<shortname>firefox</shortname>
<description>Leading Open Source internet browser.</description>
<version>3.6.3-1</version>
<license name="Firefox EULA">http://www.mozilla.com/en-US/legal/eula/firefox-en.html</license>
<ms-license>False</ms-license>
<vendor>Mozilla Foundation</vendor>
<homepage>http://www.mozilla.org/firefox</homepage>
<icon>resources/firefox.png</icon>
<download>http://download.mozilla.org/?product=firefox-3.6.3&os=win&lang=en-GB</download>
<crack required="0"/>
<install>scripts/install.sh</install>
<postinstall name="Clean Up"></postinstall>
<run>C:\\Program Files\\Mozilla Firefox\\firefox.exe</run>
<uninstall>c:\\Program Files\\Mozilla Firefox\\uninstall\\helper.exe /S</uninstall>
<requires name="autohotkey" />
</ApplicationPack>
a source to share
>>> from lxml import etree
>>> treetop = etree.fromstring(anxmlstring)
converts xml to string to Python data structure and therefore
>>> othertree = etree.parse(somexmlurl)
where somexmlurl
is the path to the local XML file or the URL of the XML file on the Internet.
The Python data structure provided by these functions (known as the "element tree", hence the module name etree
) is well documented here - all the classes, functions, methods, etc. that are referred to in the Python data structure. It closely matches one supported in the Python standard library, by the way.
If you need some other Python data structure, you will have to go through the Python data structure that lxml will return as above and build your own data structure yourself based on the information gathered in this way; lxml can't help you specifically, except that it offers several helpers for finding information in the parsed structure that it returns, so gathering said information is flexible and straightforward (again, see the documentation url above).
a source to share
It's not entirely clear what data structure you're looking for, but here's a link to sample code for converting XML to a python dictionary of lists via lxml.etree
.
a source to share