Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: xml.etree.elementtree.ElemenTtree.write() declaration tag

Tags:

python

xml

I’ve created an XML document using xml.etree.elementtree.Element, and wanted to print it using the ElementTree.write() function but the declaration tag that comes out is

<?xml version='1.0' encoding='UTF-8'?>

While I need to be in double quotes. is there a way to change that?

like image 714
Bg1987 Avatar asked May 06 '12 14:05

Bg1987


People also ask

What is Etree in Python?

The xml.etree.ElementTree module implements a simple and efficient API for parsing and creating XML data. Changed in version 3.3: This module will use a fast implementation whenever available.

How do you parse an XML string in Python?

There are two ways to parse the file using 'ElementTree' module. The first is by using the parse() function and the second is fromstring() function. The parse () function parses XML document which is supplied as a file whereas, fromstring parses XML when supplied as a string i.e within triple quotes.

How do you read a specific tag in an XML file in Python?

Example Read XML File in Python To read an XML file, firstly, we import the ElementTree class found inside the XML library. Then, we will pass the filename of the XML file to the ElementTree. parse() method, to start parsing. Then, we will get the parent tag of the XML file using getroot() .


1 Answers

I had the same problem, looked in the code of the ElementTree.py and saw the following.

For the root tag (single quotes):

        if method == "xml":
            write("<?xml version='1.0' encoding='%s'?>\n" % encoding)

And for the attributes (double quotes):

write(" %s=\"%s\"" % (qnames[k], v))

It's hardcoded that way...

I changed it (locally) to:

"<?xml version=\"1.0\" encoding=\"%s\"?>\n"

So every attribute is double quoted now.

like image 200
Stephan Schielke Avatar answered Oct 07 '22 11:10

Stephan Schielke