我遇到了xml.dom.minidom python包的奇怪问题。我生成一个文档,用从终端获取的数据填充它。有时这些数据包含终端控制字符。当我将这样的字符存储在带有minidom.toprettyxml()
的文本数据节点中时,一切似乎都很好,但是,生成的文档不是有效的XML。
有谁知道为什么minidom允许生成无效文档?这与“迷你”部分有关吗?
以下是提取的示例代码(也包含一些系统信息):
Python 2.6.5 (r265:79063, Apr 16 2010, 13:57:41)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from xml.dom import minidom
>>> impl = minidom.getDOMImplementation()
>>> doc = impl.createDocument(None, "results", None)
>>> root = doc.firstChild
>>> outString = "test "+chr(1) #here goes control character
>>> root.appendChild(doc.createTextNode(outString))
<DOM Text node "'test \x01'">
>>> doc.toprettyxml(encoding="utf-8")
'<?xml version="1.0" encoding="utf-8"?>\n<results>\n\ttest \x01\n</results>\n'
>>> with open("/tmp/outfile", "w") as f:
... f.write(doc.toprettyxml(encoding="utf-8"))
...
>>> doc2 = minidom.parse("/tmp/outfile")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.6/xml/dom/minidom.py", line 1918, in parse
return expatbuilder.parse(file)
File "/usr/lib/python2.6/xml/dom/expatbuilder.py", line 924, in parse
result = builder.parseFile(fp)
File "/usr/lib/python2.6/xml/dom/expatbuilder.py", line 207, in parseFile
parser.Parse(buffer, 0)
xml.parsers.expat.ExpatError: not well-formed (invalid token): line 3, column 6
>>> open("/tmp/outfile","r").readlines()
['<?xml version="1.0" encoding="utf-8"?>\n', '<results>\n', '\ttest \x01\n', '</results>\n']
>>>
答案 0 :(得分:1)
查看_write_data的代码,它只会转换&符号,斜杠和括号:
def _write_data(writer, data):
"Writes datachars to writer."
data = data.replace("&", "&").replace("<", "<")
data = data.replace("\"", """).replace(">", ">")
writer.write(data)
正如您所推测的那样,minidom并不是一个完全健壮的实现(例如,它缺乏名称空间的实现)。