xml到Python数据结构使用lxml

时间:2010-04-30 21:09:18

标签: python xml data-structures lxml

如何使用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&amp;os=win&amp;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>

2 个答案:

答案 0 :(得分:5)

>>> 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)。

答案 1 :(得分:0)

目前尚不清楚您正在寻找什么样的数据结构,但这里有一个代码示例的链接,可通过lxml.etree转换XML to python dictionary of lists