[英]How to write xml file with multiple root element using ElementTree in python
[英]How to write unescaped string to a XML element with ElementTree?
我有一个具有以下值的字符串变量contents
:
<ph type="0" x="1"></ph>
我尝试将其写入XML元素,如下所示:
elemen_ref.text = contents
将XML树写入文件并使用Notepad ++对其进行检查后,我看到将以下值写入XML元素:
<ph type="0" x="1"></ph>
如何编写未转义的字符串? 请注意,此值是从另一个XML元素复制而来的,该树在将树写入文件后仍保持原样,因此问题在于将值分配给text
属性。
您正在尝试这样做:
import xml.etree.ElementTree as ET
root = ET.Element('root')
content_str = '<ph type="0" x="1"></ph>'
root.text = content_str
print(ET.tostring(root))
# <root><ph type="0" x="1"></ph></root>
这实际上是将XML“注入”到元素的text属性。 这不是执行此操作的正确方法。
相反,您应该将content
字符串转换为可以附加到现有XML节点的实际XML节点。
import xml.etree.ElementTree as ET
root = ET.Element('root')
content_str = '<ph type="0" x="1"></ph>'
content_element = ET.fromstring(content_str)
root.append(content_element)
print(ET.tostring(root))
# <root><ph type="0" x="1" /></root>
如果您坚持使用,可以使用unescape
:
import xml.etree.ElementTree as ET
from xml.sax.saxutils import unescape
root = ET.Element('root')
content_str = '<ph type="0" x="1"></ph>'
root.text = content_str
print(unescape(ET.tostring(root).decode()))
# <root><ph type="0" x="1"></ph></root>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.