繁体   English   中英

如何使用lxml创建带有文本的对象化元素

[英]How to create an objectified element with text with lxml

我想用lxml.objectify创建一个元素树(不是解析!),它可能看起来像这样:

<root>
  <child>Hello World</child>
</root>

我的第一次尝试是编写这样的代码:

import lxml.objectify as o
from lxml.etree import tounicode
r = o.Element("root")
c = o.Element("child", text="Hello World")
r.append(c)
print(tounicode(r, pretty_print=True)

但这会产生:

<root xmlns:py="http://codespeak.net/lxml/objectify/pytype" 
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
      xmlns:xsd="http://www.w3.org/2001/XMLSchema" py:pytype="TREE">
  <child text="Hello World" data="Test" py:pytype="TREE"/>
</root>

正如其他答案中所建议的那样, <child>没有方法_setText

显然, lxml.objectifiy不允许创建带有文本的元素或更改文本内容。 那么,我错过了什么吗?

文档和您链接的答案。 您应该使用SubElement

r = o.E.root()    # same as o.Element("root")
c = o.SubElement(r, "child")
c._setText("Hello World")
print(tounicode(r, pretty_print=True))

c._setText("Changed it!")
print(tounicode(r, pretty_print=True))

输出:

<root xmlns:py="http://codespeak.net/lxml/objectify/pytype" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <child>Hello World</child>
</root>

<root xmlns:py="http://codespeak.net/lxml/objectify/pytype" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <child>Changed it!</child>
</root>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM