我正在尝试以一种可以读回的方式将一些数据序列化为xml。我是通过手工构建DOM来实现的xml.dom.minidom,并使用包含的writexml方法将其写入文件。在
我特别感兴趣的是如何构建文本节点。我通过初始化一个文本对象,然后设置它的data属性来实现这一点。我不确定为什么文本对象不在构造函数中接受它的内容,但这只是它在中的简化方式xml.dom.minidom. 在
举一个具体的例子,代码如下所示:
import xml.dom.minidom as dom
e = dom.Element('node')
t = dom.Text()
t.data = "The text content"
e.appendChild(t)
dom.parseString(e.toxml())
这在我看来是合理的,尤其是createTextNode本身的实现方式与此完全相同:
^{pr2}$问题是这样设置数据可以让我们写入以后无法解析的文本。举个例子,我对以下角色有困难:
you´ll
引号是ord(180),'\xb4'。我的问题是,将这些数据编码成xml文档的正确过程是什么?我用minidom解析文档以恢复原始树?在
正如Python的online docs中所述,您遇到的问题是Unicode编码:
因此,调用
^{pr2}$.toxml('utf8')
,而不仅仅是.toxml()
,并使用unicode字符串作为文本内容,您应该可以根据需要进行“往返”。例如:相关问题 更多 >
编程相关推荐