Home > other >  Get xml value of ElementTree Element
Get xml value of ElementTree Element

Time:11-18

I would like to get the xml value of an element in ElementTree. For example, if I had the code:

<?xml version="1.0" encoding="UTF-8"?>
<item>
<child>asd</child>
hello world
<ch>jkl</ch>
</item>

It would get me

<child>asd</child>
hello world
<ch>jkl</ch>

Here's what I tried so far:

import xml.etree.ElementTree as ET
root = ET.fromstring("""<?xml version="1.0" encoding="UTF-8"?>
<item>
<child>asd</child>
hello world
<ch>jkl</ch>
</item>""")
print(root.text)

CodePudding user response:

Try

print(ET.tostring(root.find('.//child')).decode(),ET.tostring(root.find('.//ch')).decode())

Or, more readable:

elems = ['child','ch']
for elem in elems:
    print(ET.tostring(doc.find(f'.//{elem}')).decode())

The output, based on the xml in your question, should be what you're looking for.

CodePudding user response:

Building on Jack Fleeting's answer, I created a solution I feel is more general, not just relating to the xml I inserted.

import xml.etree.ElementTree as ET
root = ET.fromstring("""<?xml version="1.0" encoding="UTF-8"?>
<item>
<child>asd</child>
hello world
<ch>jkl</ch>
</item>""")
for elem in root:
    print(ET.tostring(root.find(f'.//{elem.tag}')).decode())
  • Related