xml到Python数据结构使用lxml

Sam*_*lor 2 python xml lxml data-structures

如何使用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>
Run Code Online (Sandbox Code Playgroud)

Ale*_*lli 5

>>> from lxml import etree
>>> treetop = etree.fromstring(anxmlstring)
Run Code Online (Sandbox Code Playgroud)

将字符串中的xml转换为Python数据结构,同样如此

>>> othertree = etree.parse(somexmlurl)
Run Code Online (Sandbox Code Playgroud)

其中somexmlurl是本地XML文件的路径或Web上的XML文件的URL.

这些函数提供的Python数据结构(称为"元素树",etree模块名称)在这里有详细记录- 所涉及的Python数据结构支持的所有类,函数,方法等.顺便说一下,它与Python标准库中支持的内容非常匹配.

如果你想要一些不同的 Python数据结构,你将需要遍历lxml返回的Python数据结构,如上所述,并根据收集的信息自己构建不同的数据结构; lxml不能特别帮助你,除了提供几个助手来查找它返回的解析结构中的信息,因此收集所述信息是一项灵活,简单的任务(同样,请参阅上面的文档URL).