我编写了一个将 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="<p>Hi, I'm not really a person.</p>

<p>I'm a background process that helps keep this site clean!</p>

<p>I do things like</p>

<ul>
<li>Randomly poke old unanswered questions every hour so they get some attention</li>
<li>Own community questions and answers so nobody gets unnecessary reputation from them</li>
<li>Own downvotes on spam/evil posts that get permanently deleted</li>
<li>Own suggested edits from anonymous users</li>
<li><a href="http://meta.stackexchange.com/a/92006">Remove abandoned questions</a></li>
</ul>
" Views="0" UpVotes="3732" DownVotes="2275" AccountId="-1" />
</users>
解析器的相关代码是这样的:
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', '
')
我基本上包装了调用以获取转义周围的属性值 上面的功能。像这样:
res = res + '"' + escape_str(elem.attrib[c]) + '",'
请您参考如下方法:
属性中没有转义的 HTML。
属性中有 HTML,这正是您检索其值时得到的内容。
比较:
<row AboutMe="<b> This is HTML </b>" />
Attribute value: "<b> This is HTML </b>"
和:
<row AboutMe="&lt;b&gt; This is escaped HTML &lt;/b&gt;" />
Attribute value: "<b> This is escaped HTML </b>"
你的错误在于你期待错误的事情,而正确的事情却发生了。 cElementTree 绝对不不转义任何东西。它逐字为您提供属性。
