The easiest way I know is recursion. You can also use a etree transversal
method but I like controlling everything. Here is how I would do it.
After copying and fixing any bugs the next 3 functions. Just do:
walkTree(note)
Then you will have an elementList you can spin through in order.
elementList=[]
def parseTag(child):
prefix, has_namespace, postfix = child.tag.partition("}")
if has_namespace:
return postfix
return child.tag
def addChild(child):
tag = self.parseTag(child)
attr = child.attrib
text = child.text
tail = child.tail
elementList.append((tag, text,tail,attr))
def walkTree(elem):
"""recursively walks tree and creates elements in order."""
tag = self.parseTag(elem)
addChild(elem)
for nextChild in elem:
walkTree(nextChild)
From: program-l-bounce@xxxxxxxxxxxxx <program-l-bounce@xxxxxxxxxxxxx> On
Behalf Of reynoldsdavid46@xxxxxxxxx
Sent: Monday, November 7, 2022 11:29 AM
To: program-l@xxxxxxxxxxxxx
Subject: [program-l] Python XML accessing data in sub elements
Hi,
Here is my code so far:
<code begins>
import xml.etree.ElementTree as ET
mytree=ET.parse("away in a manger.xml")
myroot=mytree.getroot()
p=0
for note in myroot.iter("pitch"):
<code ends>
This iterates through all the pitch elements in the file correctly, but I
need to access sub elements of pitch, i.e. extract the data from those sub
elements.
Any help much appreciated.
David.?