How to write unescaped string to a XML element with ElementTree?

点点圈 提交于 2021-02-08 08:23:13

问题


I have a string variable contents with following value:

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

I try to write it to a XML element as follows:

elemen_ref.text = contents

After I write XML tree to a file and check it with Notepad++, I see following value written to the XML element:

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

How do I write unescaped string? Please note that this value is copied from another XML element which remains intact after writing tree to a file, so the issue is with assigning value to a text attribute.


回答1:


You are attempting to do this:

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>

Which is essentially "injecting" XML to an element's text property. This is not the correct way to do this.

Instead, you should convert the content string to an actual XML node that can be appended to the existing XML node.

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>

If you insist, you can use 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>


来源:https://stackoverflow.com/questions/53691955/how-to-write-unescaped-string-to-a-xml-element-with-elementtree

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