I am using lxml to modify an xml. In the following code, I want to delete the child of all "heading" element and assign the child text to its parent.
originally
<heading><whateverchildvalue>TEXTIWANT</whateverchildvalue></heading>
to
<heading>TEXTIWANT</heading>)
I tried to use loop for this, however somehow when I call node.remove(attr_children[0]), it jumps out of the loop and proceed to the next call of "ET.tostring(parsed)" (?) and did not modify the second "heading". To understand this, remove the "node.remove(attr_children[0])" and re-run the following code and compare the previous version of what was printed. What am I doing wrong here so that it can do a proper loop, and assign the child text to "heading" parent for all "heading" element in the xml string ?
xml_string="""
<note>
<to>Tove</to>
<mybigheader>
<heading><deleteme>Jani</deleteme></heading>
<heading><wantkey>Reminder</wantkey></heading>
</mybigheader>
<body>Don't forget me this weekend!</body>
</note>
"""
def modif_xml(xml_string):
parsed = ET.fromstring(xml_string)
for node in parsed.iter():
print "node is ", node
if "heading" in node.tag:
attr_children = node.getchildren()
for i in attr_children:
child_tag = i.tag
child_value = i.text
node.remove(attr_children[0])
node.text = child_value
my_xml = ET.tostring(parsed)
root = ET.XML(my_xml)
print ET.tostring(root, pretty_print=True)
modif_xml(xml_string)