如何使用ElementTree将未转义的字符串写入XML元素? [英] How to write unescaped string to a XML element with ElementTree?

查看:51
本文介绍了如何使用ElementTree将未转义的字符串写入XML元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a string variable contents with following value:

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

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

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

elemen_ref.text = contents

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

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;

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

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.

推荐答案

您正在尝试执行以下操作:

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>

这实际上是将XML注入"元素的text属性.这不是正确的方法.

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

相反,您应该将 content 字符串转换为可以附加到现有XML节点的实际XML节点.

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>

这篇关于如何使用ElementTree将未转义的字符串写入XML元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆