如何使用ElementTree将未转义的字符串写入XML元素?

时间:2018-12-09 11:40:46

标签: python xml-parsing elementtree

我有一个字符串变量contents,其值如下:

<ph type="0" x="1"></ph>

我尝试将其写入XML元素,如下所示:

elemen_ref.text = contents

将XML树写入文件并使用Notepad ++对其进行检查后,我看到将以下值写入XML元素:

&lt;ph type="0" x="1"&gt;&lt;/ph&gt;

如何编写未转义的字符串?请注意,此值是从另一个XML元素复制的,该XML元素在将树写入文件后保持不变,因此问题在于将值分配给text属性。

1 个答案:

答案 0 :(得分:2)

您正在尝试这样做:

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>&lt;ph type="0" x="1"&gt;&lt;/ph&gt;</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>
相关问题