在python中读取其转义表单中的xml节点属性

时间:2012-02-03 09:56:44

标签: python xml

<xmlnode id=2 text='&quot;Hello World!&quot;' />

如何在python中读取没有unescaping的“Hello World”。我正在使用像这样的ElementTree

xmlstr = """\
         <?xml version="1.0" encoding="utf-8"?>
         <nodes>
         <xmlnode id=1 text='&quot;Hello World!&quot;' />
         <xmlnode id=2 text='&quot;Hello World!&quot;' />
         </nodes>
         """
elem = ElementTree.fromstring(xmlstr)
nodes = elem.findall('xmlnode')
for row in nodes:
    print str(row.get('id'))+ ": " + row.get('text')

输出

1: "Hello World"
2: "Hello World"

我想要

1: &quot;Hello World&quot;
2: &quot;Hello World&quot;

1 个答案:

答案 0 :(得分:0)

尝试使用预先准备好的陈述:

# set up database cursor...
sql   = "INSERT foo (id, text) VALUES (%d, %s)"
elem  = ElementTree.fromstring(xmlstr)
nodes = elem.findall('xmlnode')
for row in nodes:
    valueList = (row.get('id'), row.get('text'))
    cursor.execute(sql, valueList)

如上所述,我不认为将转义值存储在数据库中会对您有所帮助。使用数据库中的实际值,它将使您的生活变得更加轻松。