An Element object has two attributes of interest here:
text is the first text node inside the element, that is, the text between the opening tag and the first child element.tail is the text node immediately following the element, that is, the text between the closing tag and the next tag (opening or closing). ElementTree.tostring() prints the tail as well.So all you need is this:
import xml.etree.ElementTree as ET
root = ET.parse('sample.xml').getroot()
for child in root:
output = child.text
for grandchild in child:
output += ET.tostring(grandchild, encoding="unicode")
print(output)
Output is:
My name is <b>Wrufesh</b>. What is yours?