0
import xml.dom.minidom

text='2 > 1'

impl = xml.dom.minidom.getDOMImplementation()
doc = impl.createDocument(None, "foobar", None)
docElem = doc.documentElement
text = doc.createTextNode(text)
docElem.appendChild(text)

f=open('foo.xml', 'w')
doc.writexml(f)
f.close()

我希望 foo.xml 如下所示:

<?xml version="1.0" ?><foobar>2 &gt; 1</foobar>

但实际上它是这样写的:

<?xml version="1.0" ?><foobar>2 &amp;gt; 1</foobar>

如何阻止 minidom 转义已经转义的序列?在我的应用程序中,文本是从(非 xml)文档中读取的,所以我不能简单地编写text = '2 > 1'.

4

1 回答 1

2

Unescape before inserting:

from xml.sax.saxutils import unescape

text = doc.createTextNode(unescape(text))

The escaping takes place when writing and cannot be disabled, nor should it be. Sometimes you want to include literal &gt; text in your XML, and that should be escaped properly for you if you do. If your input is XML escaped, simply unescape it before inserting.

于 2013-05-02T13:25:24.440 回答