3

我目前的代码是

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>

在我使用它的应用程序中,我可以轻松地使用文本替换来解决这个问题,但是如果知道如何使用库来解决这个问题会很好。

4

2 回答 2

3

我不太熟悉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

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它来生成它。

于 2014-04-02T01:05:41.873 回答
1

我认为您不能将数据写入根元素。您可能需要像这样创建一个子元素:

xml_obj = lxml.objectify.Element('root_name')
xml_obj.child_name = str('text')
lxml.etree.tostring(xml_obj)
于 2014-04-01T23:44:05.717 回答