[英]How do you create a non-nested xml element using Python's lxml.objectify?
我目前的代码是
xml_obj = lxml.objectify.Element('root_name')
xml_obj[root_name] = str('text')
lxml.etree.tostring(xml_obj)
但是这会创建以下xml:
<root_name><root_name>text</root_name></root_name>
在我使用它的应用程序中,我可以轻松地使用文本替换来解决这个问题,但知道如何使用库来做它会很好。
我不熟悉objectify
,但我认为这不是它的用途。 它表示对象的方式是,任何给定级别的节点都是一个类名,子节点是字段名(带有类型)和值。 而使用它的正常方式更像是这样的:
xml_obj = lxml.objectify.Element('xml_obj')
xml_obj.root_path = 'text'
etree.dump(xml_obj)
<root_name 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">
<root_name py:pytype="str">text</root_name>
</root_name>
你想要的是使用etree
更容易做到的etree
:
xml_obj = lxml.etree.Element('root_path')
xml_obj.text = 'text'
etree.dump(xml_obj)
<root_path>text</root_path>
如果你真的需要它是objectify
,看起来你不应该直接混合,你可以使用tostring
生成XML,然后objectify.fromstring
将它带回来。 但可能,如果这是你想要的,你应该只使用etree
来生成它。
我认为你不能将数据写入根元素。 您可能需要创建一个这样的子元素:
xml_obj = lxml.objectify.Element('root_name')
xml_obj.child_name = str('text')
lxml.etree.tostring(xml_obj)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.