如何使用lxml创建文本节点? [英] How to create a Text Node with lxml?
问题描述
我正在使用lxml和python处理xml文件.我想创建一个最好没有标签的文本节点,而不是创建一个新的Element
,然后向其添加文本.我该怎么办?
I'm using lxml and python to manipulate xml files. I want to create a text node with no tags preferably, instead of creating a new Element
and then append a text to it. How can I do that?
我可以在名为createTextNode
的python xml.dom.minidom
包中找到与之等效的东西,所以我想知道lxml是否支持相同的功能?
I could find an equivalent of this in xml.dom.minidom
package of python called createTextNode
, so I was wondering if lxml supports same functionality or not?
推荐答案
看起来lxml
没有提供用于创建文本节点的特殊API.您只需设置父元素的text
属性即可在该元素中创建或修改文本节点,例如:
Looks like lxml
doesn't provide a special API to create text node. You can simply set text
property of a parent element to create or modify text node in that element, for example :
>>> from lxml import etree
>>> raw = '''<root><foo/></root>'''
>>> root = etree.fromstring(raw)
>>> root.text = 'bar'
>>> etree.tostring(root)
'<root>bar<foo/></root>'
这篇关于如何使用lxml创建文本节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!