如何输出XML实体引用 [英] How to output XML entity references
问题描述
我正在使用Python xml.etree.ElementTree输出XML。我想输出带有在解析XML时将被替换的实体引用。
I am using Python xml.etree.ElementTree to output XML. I want to output it with entity references that will be substituted when the XML is parsed.
通常'&'被转义为& amp ;
,因为'&'用于声明实体引用。但是,我确实要做要编写一个实体引用。例如,我要编写一个包含实体引用& manifestName;
的XML文件:
ordinarily '&' is escaped as &
because '&' is used to declare entity references. However, I really do want to write an entity reference. For example, I want to write an XML file containing the entity reference &manifestName;
:
>>> from xml.etree.ElementTree import Element, tostring
>>> manifest = Element('manifest')
>>> manifest.text = '&manifestName;'
>>> tostring(manifest)
返回一个逃逸的&符:
'<manifest>&manifestName;</manifest>'
所需的XML将是:
'<manifest>&manifestName;</manifest>'
我尝试了各种转义技巧,例如&# 38;
, \&
,&&
,但它们没有工作。它们包含的与符号始终呈现为&
。
I have tried various escaping tricks, like &
, \&
, &&
, but they do not work. The ampersands they contain are always rendered as &
.
推荐答案
我决定采用相对可口的破解方法。在文本中,我使用&
表示逃脱的&
。 ElementTree将此转换为&&
。最后,我只是对其进行字符串替换:
I have decided to go with a relatively palatable hack. In the text, I use &&
to mean an escaped &
. ElementTree converts this to &&
. At the end, I simply do a string replacement on it:
>>> from xml.etree.ElementTree import Element, tostring
>>> manifest = Element('manifest')
>>> manifest.text = '&&manifestName;'
>>> tostring(manifest).replace('&&', '&')
结果是我想要的实体引用:
The result is the entity reference I want:
'<manifest>&manifestName;</manifest>'
这篇关于如何输出XML实体引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!