我创建了下一个XML:
item = E('p') # <p/>
现在我需要将下一个内容放入其中:
text = "some <bold>text</bold>"
# item.append(text)
# TypeError: Argument 'element' has incorrect type (expected lxml.etree._Element, got str)
# item.append(fromstring(text))
# lxml.etree.XMLSyntaxError: Start tag expected, '<' not found, line 1, column 1
我需要下一个XML节点作为结果:
<p>some <bold>text</bold></p>
如何正确地做到这一点?
答案 0 :(得分:2)
您需要创建子元素:
from lxml import etree
root = etree.Element("p")
root.text = 'some'
bold = etree.SubElement(root, 'bold')
bold.text = 'text'
print (etree.tostring(root))
返回:
<p>some<bold>text</bold></p>