Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a Python XML ElementTree to a String

I need to convert an XML ElementTree to a String after altering it. It's the toString part that isn't working.

import xml.etree.ElementTree as ET

tree = ET.parse('my_file.xml')
root = tree.getroot()

for e in root.iter('tag_name'):
    e.text = "something else" # This works

# Now I want the the complete XML as a String with the alteration

I've tried various versions of the below line, with ET or ElementTree as various names, and importing toString, etc. etc,

s = tree.tostring(ET, encoding='utf8', method='xml')

I have seen Convert Python ElementTree to string and some others, but I'm not sure how to apply it to my example.

like image 683
user984003 Avatar asked Nov 19 '15 21:11

user984003


People also ask

How do you convert an element tree to a string?

In most scenarios, using str() would be the "cannonical" way to convert an object to a string. Unfortunately, using this with Element returns the object's location in memory as a hexstring, rather than a string representation of the object's data. In Python 2 ElementTree. tostring() also generates a bytestring.

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 I print a pretty XML string in Python?

Use lxml. etree.parse(source) to parse the XML file source and return an ElementTree object. Call lxml. etree. tostring(element_or_tree, encoding="unicode" pretty_print=True) to pretty print the contents of the XML file, with element_or_tree as the result of the previous step.


1 Answers

This should work:-

xmlstr = ET.tostring(root, encoding='utf8', method='xml')
like image 97
Stephen Briney Avatar answered Sep 21 '22 12:09

Stephen Briney