python - 使用 lxml 将 xml 转换为 Python 数据结构

标签 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>

最佳答案

>>> 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/

相关文章:

python - 如何仅使用 str.format 在 python3 中截断和填充?

algorithm - 弗洛伊德的循环查找算法 while checks

c++ - 如何让你的数据结构接受任何类的对象 - C++

c - 如何节省数组中未使用的空间?

python - 基于外键django Rest框架序列化数组数据

python - pycharm 自动完成 "print()"而不是 "print"

python - 在流程开始执行后(在完成之前)向 subprocess.Popen() 提供标准输入

xml - 在 XSL 中,如何根据多个属性选择一个值?

导致问题的 XML '&' 字符

java - 处理 RPC/编码 Web 服务中的 SOAP 编码