问题
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?
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?
回答1:
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>'
来源:https://stackoverflow.com/questions/36570460/how-to-create-a-text-node-with-lxml