问题
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:
<ph type="0" x="1"></ph>
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><ph type="0" x="1"></ph></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