如何确保xml.dom.minidom能解析其自身输出?

0 投票
1 回答
2628 浏览
提问于 2025-04-15 12:04

我正在尝试把一些数据转成XML格式,这样以后可以再读取回来。我是通过手动构建一个DOM(文档对象模型)来实现的,使用的是xml.dom.minidom这个库,然后用里面的writexml方法把它写入文件。

我特别想说的是我怎么构建文本节点。我是先初始化一个文本对象,然后设置它的数据属性。我不太明白为什么文本对象在创建的时候不直接接受内容,但这就是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的实现方式和这个完全一样:

def createTextNode(self, data):
    if not isinstance(data, StringTypes):
        raise TypeError, "node contents must be a string"
    t = Text()
    t.data = data
    t.ownerDocument = self
    return t

问题是,像这样设置数据会导致我们写入的文本在之后无法再解析回来。举个例子,我在处理以下字符时遇到了困难:

you´ll

这个字符的编码是ord(180),也就是'\xb4'。我的问题是,怎样才能正确地把这些数据编码成XML文档,以便我用minidom解析这个文档时能恢复原来的结构呢?

1 个回答

3

你遇到的问题,正如Python的在线文档中所解释的,是关于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字符串,这样你就可以顺利完成你想要的“往返”操作了。例如:

>>> t.data = u"The text\u0180content"
>>> dom.parseString(e.toxml('utf8')).toxml('utf8')
'<?xml version="1.0" encoding="utf8"?><node>The text\xc6\x80content</node>'
>>> 

撰写回答