如何使用 lxml 将 xml 转换为 Python 数据结构?
我到处寻找,但什么也没找到。
输入示例
<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>
最佳答案
>>> from lxml import etree
>>> treetop = etree.fromstring(anxmlstring)
将字符串中的xml转换为Python数据结构,同样如此
>>> othertree = etree.parse(somexmlurl)
其中 somexmlurl
是本地 XML 文件的路径或 Web 上 XML 文件的 URL。
这些函数提供的 Python 数据结构(称为“元素树”,etree
模块名称由此而来)已有详细记录 here -- 相关 Python 数据结构支持的所有类、函数、方法等。顺便说一下,它与 Python 标准库中支持的库非常匹配。
如果你想要一些不同的Python数据结构,你必须遍历lxml返回的Python数据结构,如上所述,并根据这些信息自己构建不同的数据结构集; lxml 不能专门帮助您,除了提供几个帮助程序来在它返回的解析结构中查找信息,以便收集所述信息是一项灵活、简单的任务(再次参见上面的文档 URL)。
关于python - 使用 lxml 将 xml 转换为 Python 数据结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2747712/