Skip to main content
 首页 » 编程设计

Python ElementTree 转义 HTML 实体

2024年10月25日9qlqwjy

我编写了一个将 XML 解析为逗号分隔格式的简单脚本。一个 sample XML 源代码如下所示:

<?xml version="1.0" encoding="utf-8"?> 
<users> 
<row Id="-1" Reputation="1" CreationDate="2010-08-10T15:50:26.953" DisplayName="Community" LastAccessDate="2010-08-10T15:50:26.953" Location="on the server farm" AboutMe="&lt;p&gt;Hi, I'm not really a person.&lt;/p&gt;&#xA;&#xA;&lt;p&gt;I'm a background process that helps keep this site clean!&lt;/p&gt;&#xA;&#xA;&lt;p&gt;I do things like&lt;/p&gt;&#xA;&#xA;&lt;ul&gt;&#xA;&lt;li&gt;Randomly poke old unanswered questions every hour so they get some attention&lt;/li&gt;&#xA;&lt;li&gt;Own community questions and answers so nobody gets unnecessary reputation from them&lt;/li&gt;&#xA;&lt;li&gt;Own downvotes on spam/evil posts that get permanently deleted&lt;/li&gt;&#xA;&lt;li&gt;Own suggested edits from anonymous users&lt;/li&gt;&#xA;&lt;li&gt;&lt;a href=&quot;http://meta.stackexchange.com/a/92006&quot;&gt;Remove abandoned questions&lt;/a&gt;&lt;/li&gt;&#xA;&lt;/ul&gt;&#xA;" Views="0" UpVotes="3732" DownVotes="2275" AccountId="-1" /> 
</users> 

gist

解析器的相关代码是这样的:

import xml.etree.cElementTree as cetree 
 
def get_data_c(fn, columns): 
    res = '' 
    cols = columns.split(',') 
 
    for c in cols: 
        res = res + c + ',' 
 
    res = res[:-1] + '\n' 
    yield res 
 
    for event, elem in cetree.iterparse(fn): 
        res = '' 
        if elem.tag == "row": 
            for c in cols: 
                if c in elem.attrib: 
                    res = res + elem.attrib[c] + ',' 
                else: 
                    res = res + ',' 
            res = res[:-1] + '\n' 
            yield res 
            elem.clear() 

gist完整的脚本。

我的问题是,当我获得 AboutMe 属性的值时,cElementTree 正在对该属性中包含的 HTML 进行转义。理想情况下,我想 保持格式为转义 HTML,并简单地将其用引号括起来以供输出 文件。但是我得到的是未转义的字符串,如此处所示 gist .我怎么说 cElementTree 保持属性的原始值不进行变换 它到 HTML?

EDIT 2014-09-01 12:49 PST:根据下面 Tomalak 的回答,这就是我用来获得我正在寻找的行为的方法:

def escape_str(html_str): 
    s = html.escape(html_str) 
    return s.replace('\n', '&#xA;') 

我基本上包装了调用以获取转义周围的属性值 上面的功能。像这样:

res = res + '"' + escape_str(elem.attrib[c]) + '",' 

请您参考如下方法:

属性中没有转义的 HTML。

属性中有 HTML,这正是您检索其值时得到的内容。

比较:

<row AboutMe="&lt;b&gt; This is HTML &lt;/b&gt;" /> 
 
Attribute value: "<b> This is HTML </b>" 

和:

<row AboutMe="&amp;lt;b&amp;gt; This is escaped HTML &amp;lt;/b&amp;gt;" /> 
 
Attribute value: "&lt;b&gt; This is escaped HTML &lt;/b&gt;" 

你的错误在于你期待错误的事情,而正确的事情却发生了。 cElementTree 绝对不不转义任何东西。它逐字为您提供属性。