如何将 XML 转换为 Python 对象? [英] How can I convert XML into a Python object?
本文介绍了如何将 XML 转换为 Python 对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要加载一个 XML 文件并将内容转换为面向对象的 Python 结构.我想拿这个:
I need to load an XML file and convert the contents into an object-oriented Python structure. I want to take this:
<main>
<object1 attr="name">content</object>
</main>
然后把它变成这样:
main
main.object1 = "content"
main.object1.attr = "name"
XML 数据将具有比这更复杂的结构,我无法对元素名称进行硬编码.解析时需要收集属性名称,作为对象属性使用.
The XML data will have a more complicated structure than that and I can't hard code the element names. The attribute names need to be collected when parsing and used as the object properties.
如何将 XML 数据转换为 Python 对象?
How can I convert XML data into a Python object?
推荐答案
值得一看 lxml.objectify
.
xml = """<main>
<object1 attr="name">content</object1>
<object1 attr="foo">contenbar</object1>
<test>me</test>
</main>"""
from lxml import objectify
main = objectify.fromstring(xml)
main.object1[0] # content
main.object1[1] # contenbar
main.object1[0].get("attr") # name
main.test # me
或者反过来构建 xml 结构:
Or the other way around to build xml structures:
item = objectify.Element("item")
item.title = "Best of python"
item.price = 17.98
item.price.set("currency", "EUR")
order = objectify.Element("order")
order.append(item)
order.item.quantity = 3
order.price = sum(item.price * item.quantity for item in order.item)
import lxml.etree
print(lxml.etree.tostring(order, pretty_print=True))
输出:
<order>
<item>
<title>Best of python</title>
<price currency="EUR">17.98</price>
<quantity>3</quantity>
</item>
<price>53.94</price>
</order>
这篇关于如何将 XML 转换为 Python 对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文