简体   繁体   中英

Get xml value of ElementTree Element

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)

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.

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())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM