【问题标题】:Unescaping XML attributes in Python在 Python 中取消转义 XML 属性
【发布时间】:2019-01-29 15:32:06
【问题描述】:

如何转义字符串以便在 XML 属性中使用?

不是从 python 代码中以编程方式设置属性——我只需要创建一个可以用作 XML 属性的有效字符串。

我试过了:

from xml.sax.saxutils import escape, quoteattr

print (escape('<&% "eggs and spam" &>'))
# >>> &lt;&amp;% "eggs and spam" &amp;&gt;

print (quoteattr('<&% "eggs and spam" &>'))
# >>> '&lt;&amp;% "eggs and spam" &amp;&gt;'

问题在于escape()quoteattr() 都没有转义双引号字符,即"

当然,我可以对转义字符串执行.replace('"', '&amp;quot;'),但我假设应该有一种方法可以使用现有的API(来自标准库或使用第三方模块,例如lxml )。

更新:我发现 Python3 的 html.escape 产生了预期的结果,但我不愿意在 XML 上下文中使用它,因为我假设 HTML转义可能遵循不同于 XML 标准 (https://www.w3.org/TR/xml/#AVNormalize) 要求的规范。

【问题讨论】:

  • 我不明白这个问题。您是通过字符串连接构建 XML 吗?
  • @Tomalak:是的,类似的;我需要将“原始”字符串处理成随后可以以非编程方式方式插入到 XML 中的表单。
  • 以这种方式构建 XML 根本不是一个好主意,但如果您确实必须这样做,我仍然建议您使用 XML API。使用 ElementTree 或 lxml,我将使用单个元素(例如 &lt;root&gt;)创建最简单的 XML 文档,通过 API 添加属性,将文档序列化为字符串,最后从结果。总共可能只有 4 行代码。

标签: python xml escaping


【解决方案1】:

无耻地从tornado盗取(稍作修改):

import re
_XHTML_ESCAPE_RE = re.compile('[&<>"\']')
_XHTML_ESCAPE_DICT = {'&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;',
                      '\'': '&#39;'}

def xhtml_escape(value):
    """Escapes a string so it is valid within HTML or XML.

    Escapes the characters ``<``, ``>``, ``"``, ``'``, and ``&``.
    When used in attribute values the escaped strings must be enclosed
    in quotes.

    .. versionchanged:: 3.2

       Added the single quote to the list of escaped characters.
    """
    return _XHTML_ESCAPE_RE.sub(lambda match: _XHTML_ESCAPE_DICT[match.group(0)],
                                value)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-19
    • 1970-01-01
    • 1970-01-01
    • 2021-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多