如何使用Python';s lxml.objectify?
我现在的代码是如何使用Python';s lxml.objectify?,python,xml,lxml,lxml.objectify,Python,Xml,Lxml,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> 文本 在应用程序中,我使用它是因为我可以很容易地使用文本替换来解决这个问题,但是如果知道
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>
文本
在应用程序中,我使用它是因为我可以很容易地使用文本替换来解决这个问题,但是如果知道如何使用库来解决这个问题,那就太好了。我认为您无法将数据写入根元素。您可能需要创建一个子元素,如下所示:
xml_obj = lxml.objectify.Element('root_name')
xml_obj.child_name = str('text')
lxml.etree.tostring(xml_obj)
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>
我对objectify不太熟悉,但我认为这不是它的使用方式。它表示对象的方式是,任何给定级别的节点都是类名,子节点是字段名(带有类型)和值。通常的使用方法是这样的:
xml_obj = lxml.objectify.Element('root_name')
xml_obj.child_name = str('text')
lxml.etree.tostring(xml_obj)
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>
如果您确实需要将它放在
objectify
中,看起来虽然您不应该直接混合,但您可以使用tostring
生成XML,然后使用objectify.fromstring
将其带回来。但是,如果这是您想要的,您应该使用etree
生成它。谢谢!我使用Objectify是因为我熟悉它,但您对etree的看法完全正确。