2
xml.dom.minidom python 패키지에 이상한 문제가 발생했습니다. 나는 터미널에서 가져온 데이터를 채워 문서를 생성한다. 때때로 이러한 데이터에는 터미널 제어 문자가 포함됩니다. minidom.toprettyxml()
으로 텍스트 데이터 노드에 이러한 문자를 저장하면 모든 것이 잘된 것처럼 보이지만 생성 된 문서는 유효한 XML이 아닙니다.Python xml.dom.minidom이 잘못된 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']
>>>
텍스트를 CDATA 섹션으로 이동하십시오. –
가능한 여러 가지 해결 방법이 있습니다. CDATA보다 좋지만 문제는 다음과 같습니다. 왜 minidom이 잘못된 XML을 생성합니까? 버그 또는 기능입니까? (아마도 minidom의 "ligthness"와 연결되어있다) –