我编写了一个简单的脚本,将XML解析为逗号分隔的格式。一个样品 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?
编辑2014-09-01 12:49太平洋标准时间:根据以下Tomalak的回答,这就是我以前得到的行为:
def escape_str(html_str):
s = html.escape(html_str)
return s.replace('\n', '
')
我基本上打包调用以获取转义周围的属性值 以上功能。像这样:
res = res + '"' + escape_str(elem.attrib[c]) + '",'
答案 0 :(得分:2)
属性中没有转义的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肯定不 unescaping任何东西。它为您提供了逐字的属性。