PYTHON 2.6 XML.ETREE 输出属性时用单引号而非双引号

3 投票
1 回答
3177 浏览
提问于 2025-04-17 09:32

我有以下这段代码:

#!/usr/bin/python2.6  

from lxml import etree  

n = etree.Element('test')    
n.set('id','1234')  
print etree.tostring(n)  

生成的输出是 <test id="1234"/>
但我想要的是 <test id='1234'/>

有人能帮忙吗?

1 个回答

7

我查看了文档,发现没有关于单引号和双引号选项的说明。

我觉得你唯一能做的就是用 print etree.tostring(n).replace('"', "'") 这个方法。

更新

假设:

from lxml import etree
n = etree.Element('test')
n.set('id', "Zach's not-so-good answer")

我之前的回答可能会因为引号不匹配而输出格式不正确的XML:

<test id='Zach's not-so-good answer'></test>

Martijn建议使用 print etree.tostring(n).replace("'", '&apos;').replace('"', "'") 来解决这个问题:

<test id='Zach&apos;s not-so-good answer'></test>

撰写回答