[英]How do you create a non-nested xml element using Python's lxml.objectify?
My current code is 我目前的代码是
xml_obj = lxml.objectify.Element('root_name')
xml_obj[root_name] = str('text')
lxml.etree.tostring(xml_obj)
but this creates the following xml: 但是这会创建以下xml:
<root_name><root_name>text</root_name></root_name>
In the application I am using this for I could easily use text substitution to solve this problem, but it would be nice to know how to do it using the library. 在我使用它的应用程序中,我可以轻松地使用文本替换来解决这个问题,但知道如何使用库来做它会很好。
I'm not that familiar with objectify
, but i don't think that's the way it's intended to be used. 我不熟悉
objectify
,但我认为这不是它的用途。 The way it represents objects, is that a node at any given level is, say, a classname, and the subnodes are field names (with types) and values. 它表示对象的方式是,任何给定级别的节点都是一个类名,子节点是字段名(带有类型)和值。 And the normal way to use it would be something more like this:
而使用它的正常方式更像是这样的:
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>
What you want would be way easier to do with etree
: 你想要的是使用
etree
更容易做到的etree
:
xml_obj = lxml.etree.Element('root_path')
xml_obj.text = 'text'
etree.dump(xml_obj)
<root_path>text</root_path>
If you really need it to be in objectify
, it looks like while you shouldn't mix directly, you can use tostring
to generate XML, then objectify.fromstring
to bring it back. 如果你真的需要它是
objectify
,看起来你不应该直接混合,你可以使用tostring
生成XML,然后objectify.fromstring
将它带回来。 But probably, if this is what you want, you should just use etree
to generate it. 但可能,如果这是你想要的,你应该只使用
etree
来生成它。
I don't think you can write data into the root element. 我认为你不能将数据写入根元素。 You may need to create a child element like this:
您可能需要创建一个这样的子元素:
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.