【发布时间】:2018-03-25 17:40:10
【问题描述】:
使用lxml 库的objectify API 为元素设置值,默认情况下将自动检测到的pytype 分配给该元素和所需的命名空间。
例如设置根元素:
root = objectify.Element('root')
print(etree.tostring(root, pretty_print=True).decode('utf-8'))
输出:
<root xmlns:py="http://codespeak.net/lxml/objectify/pytype"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" py:pytype="TREE"/>
或为子元素设置值:
child = objectify.SubElement(root, 'child')
root.child = 'value'
print(etree.tostring(root, pretty_print=True).decode('utf-8'))
输出:
<root xmlns:py="http://codespeak.net/lxml/objectify/pytype"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" py:pytype="TREE">
<child py:pytype="str">value</child>
</root>
即使使用 ObjectPath 的 setattr:
path = objectify.ObjectPath('root.vader.son')
path.setattr(root, 'Luke')
print(etree.tostring(root, pretty_print=True).decode('utf-8'))
输出:
<root xmlns:py="http://codespeak.net/lxml/objectify/pytype"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" py:pytype="TREE">
<child py:pytype="str">value</child>
<vader>
<son py:pytype="str">Luke</son>
</vader>
</root>
有一些解决方案可以在创建元素后使用deannotate() 函数(例如When using lxml, can the XML be rendered without namespace attributes?、Remove "xmlns:py..." with lxml.objectify)删除pytype 及其命名空间。没有任何解决方案可以从一开始就创建没有pytype 及其命名空间的元素。关于如何做到这一点的任何想法?
【问题讨论】:
标签: python lxml lxml.objectify