How to output XML entity references

荒凉一梦 提交于 2020-01-14 14:50:27

问题


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.

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)

Which returns an escaped ampersand:

'<manifest>&amp;manifestName;</manifest>'

The desired XML would be:

'<manifest>&manifestName;</manifest>'

I have tried various escaping tricks, like &#38;, \&, &&, but they do not work. The ampersands they contain are always rendered as &amp;.


回答1:


I have decided to go with a relatively palatable hack. In the text, I use && to mean an escaped &. ElementTree converts this to &amp;&amp;. 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('&amp;&amp;', '&')

The result is the entity reference I want:

'<manifest>&manifestName;</manifest>'


来源:https://stackoverflow.com/questions/7986272/how-to-output-xml-entity-references

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!