How to create a Text Node with lxml?

喜你入骨 提交于 2019-12-10 23:58:28

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!