python - 如何使用 Python 的 lxml.objectify 创建非嵌套的 xml 元素?

标签 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>

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

最佳答案

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

关于python - 如何使用 Python 的 lxml.objectify 创建非嵌套的 xml 元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22798502/

相关文章:

python - Pytest 断言错误问题

java - QuickBooks java SOAP Web 连接器结构

c# - 如果在我的 WPF 项目中找不到 xml 文件,如何编写创建新的 xml?

python - 在 Python 中使用 lxml 遍历 XML 的最快/最佳方法

python - 如何替换 xml SVG 文件中每个元素的属性然后保存?

python - 用于部署单节点的 Storm 替代方案

python - 为什么必须调用 db.session.remove()?

python - 将大型训练和测试文件流式传输到 Tensorflow 的 DNNClassifier

.net - 如何阻止 .net Xml 序列化插入非法字符

python - XPath 不是 lxml 的预期结果