Seb
Seb

Reputation: 151

PYTHON 2.6 XML.ETREE to output single quote for attributes instead of double quote

i got the following code :

#!/usr/bin/python2.6  

from lxml import etree  

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

the output generate is <test id="1234"/>
but i want <test id='1234'/>

can someone help ?

Upvotes: 3

Views: 3375

Answers (1)

Zach Young
Zach Young

Reputation: 11188

I checked the documentation and found no reference for single/double-quote option.

I think your only recourse is print etree.tostring(n).replace('"', "'")

Update

Given:

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

my original answer could output malformed XML because of unbalanced apostrophes:

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

Martijn suggested print etree.tostring(n).replace("'", '&apos;').replace('"', "'") to address the problem:

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

Upvotes: 7

Related Questions