Convert XML ElementTree Python to String

I need to convert XML ElementTree to string after changing it. This is the toString part that does not work.

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 tried different versions of the line below, with ET or ElementTree, like different names, and imported toString, etc. etc.,

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

I saw Converting Python ElementTree to String and some others, but I'm not sure how to apply it to my example.

+6
source share
2 answers

This should work: -

xmlstr = ET.tostring(root, encoding='utf8', method='xml')
+6
source

How to convert ElementTree.Elementto string?

For Python 3:

xml_str = ElementTree.tostring(xml, encoding='unicode')

For Python 2:

xml_str = ElementTree.tostring(xml, encoding='utf-8')

For compatibility with Python 2 and 3:

xml_str = ElementTree.tostring(xml).decode()

from xml.etree import ElementTree

xml = ElementTree.Element("Person", Name="John")
xml_str = ElementTree.tostring(xml).decode()
print(xml_str)

:

<Person Name="John" />

, , ElementTree.tostring() Python 2 3. Python 3, Unicode .

Python 2 str . , , , . [...]

, [Python 3] , .

: Python 2 Python 3

, Python , unicode utf-8. , Python 2 3, decode() .

.tostring() Python 2 Python 3.

ElementTree.tostring(xml)
# Python 3: b'<Person Name="John" />'
# Python 2: <Person Name="John" />

ElementTree.tostring(xml, encoding='unicode')
# Python 3: <Person Name="John" />
# Python 2: LookupError: unknown encoding: unicode

ElementTree.tostring(xml, encoding='utf-8')
# Python 3: b'<Person Name="John" />'
# Python 2: <Person Name="John" />

ElementTree.tostring(xml).decode()
# Python 3: <Person Name="John" />
# Python 2: <Person Name="John" />

Martijn Peters , str Python 2 3.


str()?

str() " " . , Element , .

from xml.etree import ElementTree

xml = ElementTree.Element("Person", Name="John")
print(str(xml))  # <Element 'Person' at 0x00497A80>
+4

Source: https://habr.com/ru/post/1616630/


All Articles