如何确保xml.dom.minidom可以解析它自己的输出吗?

2024-10-06 12:36:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试以一种可以读回的方式将一些数据序列化为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解析文档以恢复原始树?在


Tags: 数据对象方法文档文本data序列化方式
1条回答
网友
1楼 · 发布于 2024-10-06 12:36:18

正如Python的online docs中所述,您遇到的问题是Unicode编码:

Node.toxml([encoding])
Return the XML that the DOM represents as a string.

With no argument, the XML header does not specify an encoding, and the result is
Unicode string if the default encoding cannot represent all characters in the 
document. Encoding this string in an encoding other than UTF-8 is likely
incorrect, since UTF-8 is the default encoding of XML.

With an explicit encoding [1] argument, the result is a byte string in the 
specified encoding. It is recommended that this argument is always specified.
To avoid UnicodeError exceptions in case of unrepresentable text data, the 
encoding argument should be specified as “utf-8”.

因此,调用.toxml('utf8'),而不仅仅是.toxml(),并使用unicode字符串作为文本内容,您应该可以根据需要进行“往返”。例如:

^{pr2}$

相关问题 更多 >