【问题标题】:etree parsing xml with escaped html insideetree解析带有转义html的xml
【发布时间】:2021-06-02 08:07:09
【问题描述】:

我有一个带有转义 html 的 xml 文件,该字段如下所示:

<title>Some records title with html <i> This should be inside escaped html </i>, end of the title</title>

我发现那个元素很好:

el = titles.find("x:title", NS)

但是当我这样做时:

el.text

它返回带有非转义标签的文本:

'Some records title with html <i> This should be inside escaped html </i>;, end of the title'

为什么会这样?即使提供了转义,我是否必须再次单独转义 html 标签?我希望能够为 xml 提供转义和非转义的 html 标签(有时将其显示为文本,有时显示为格式化文本)。如何正确提供?

【问题讨论】:

    标签: html xml elementtree


    【解决方案1】:

    在使用ElementTree函数时可以使用_escape_attrib()

    import xml.etree.ElementTree as ET
    
    text = '''<title>Some records title with html &lt;i&gt; This should be inside escaped html &lt;/i&gt;, end of the title</title>
    '''
    
    root = ET.fromstring(text)
    
    print(ET._escape_attrib(root.text))
    

    这将输出Some records title with html &amp;lt;i&amp;gt; This should be inside escaped html &amp;lt;/i&amp;gt;, end of the title

    【讨论】:

      猜你喜欢
      • 2012-02-01
      • 2014-03-27
      • 1970-01-01
      • 2015-06-26
      • 2014-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-20
      相关资源
      最近更新 更多