Try this:

from xml.etree import ElementTree as ET

xml = """<root>
  <item>Over the <ref id="river" /> and through the <ref id="woods" />.</item>
  <item>To Grandmother's <ref id="house" /> we go.</item>
</root>"""

root = ET.fromstring(xml)

for item in root:
    if item.text:
        print(item.text)
    for ref in item:
        print(ref)
        if ref.tail:
            print(ref.tail)

ElementTrees representation of "mixed content" is based on .text and .tail attributes. The .text of an element represents the text of the element up to the first child element. That child's .tail then contains the text of its parent following it. See the API doc.

Answer from dnswlt on Stack Overflow
🌐
Python
docs.python.org › 3 › library › xml.etree.elementtree.html
xml.etree.ElementTree — The ElementTree XML API
January 29, 2026 - Where immediate feedback through events is wanted, calling method XMLPullParser.flush() can help reduce delay; please make sure to study the related security notes. Element has some useful methods that help iterate recursively over all the sub-tree below it (its children, their children, and so on).
🌐
Runestone Academy
runestone.academy › ns › books › published › py4e-int › web › loopingNodes.html
15.3. Looping through nodes — Python for Everybody - Interactive
Use findall to retrieve subtrees representing user structures in the XML tree. --- Use a for each loop to loop through the user nodes --- Print the name and id from the user node --- Print the x attribute from the user node using get · It is important to include all parent level elements in the findall statement except for the top level element (e.g., users/user). Otherwise, Python will not find any desired nodes.
🌐
Python.org
discuss.python.org › python help
How to iterate through unbalanced XML hierarchy? - Python Help - Discussions on Python.org
January 23, 2025 - Greetings, I have an XML file which has an unbalanced hierarchy of nodes … some of the nodes have a sub-node of but many do not. Do you know of an easy way to read this xml into an array? I’ve tried beautifulsoup but it seems to be more oriented to strictly formed xml (at least for it’s ...
🌐
TutorialKart
tutorialkart.com › python › python-xml-parsing
XML Parsing in Python
April 5, 2023 - # Python XML Parsing import xml.etree.ElementTree as ET root = ET.parse('sample.xml').getroot() # iterate over child nodes for holiday in root.findall('holiday'): # get all attributes of a node attributes = holiday.attrib print(attributes) # get a particular attribute type = attributes.get('type') print(type)
🌐
Example Code
example-code.com › python › xml_iter_child.asp
CkPython Iterate over Direct Child Nodes by Index
Chilkat • HOME • Android™ • AutoIt • C • C# • C++ • Chilkat2-Python • CkPython • Classic ASP • DataFlex • Delphi DLL • Go • Java • Node.js • Objective-C • PHP Extension • Perl • PowerBuilder • PowerShell • PureBasic • Ruby • SQL Server • Swift • Tcl • Unicode C • Unicode C++ • VB.NET • VBScript • Visual Basic 6.0 • Visual FoxPro • Xojo Plugin
Find elsewhere
🌐
Engineering LibreTexts
eng.libretexts.org › bookshelves › computer science › programming languages › python for everybody (severance) › 13: python and web services
13.2: Looping through Nodes - Engineering LibreTexts
September 10, 2021 - Often the XML has multiple nodes and we need to write a loop to process all of the nodes. In the following program, we loop through all of the user nodes: %%python3 import xml.etree.ElementTree as ET input = ''' <stuff> <users> <user x=\"2\"> <id>001</id> <name>Chuck</name> </user> <user x=\"7\"> <id>009</id> <name>Brent</name> </user> </users> </stuff>''' stuff = ET.fromstring(input) lst = stuff.findall('users/user') print('User count:', len(lst)) for item in lst: print('Name', item.find('name').text) print('Id', item.find('id').text) print('Attribute', item.get(\"x\")) # Code: http://www.py4e.com/code3/xml2.py
Top answer
1 of 7
60

To iterate over all nodes, use the iter method on the ElementTree, not the root Element.

The root is an Element, just like the other elements in the tree and only really has context of its own attributes and children. The ElementTree has the context for all Elements.

For example, given this xml

<?xml version="1.0"?>
<data>
    <country name="Liechtenstein">
        <rank>1</rank>
        <year>2008</year>
        <gdppc>141100</gdppc>
        <neighbor name="Austria" direction="E"/>
        <neighbor name="Switzerland" direction="W"/>
    </country>
    <country name="Singapore">
        <rank>4</rank>
        <year>2011</year>
        <gdppc>59900</gdppc>
        <neighbor name="Malaysia" direction="N"/>
    </country>
    <country name="Panama">
        <rank>68</rank>
        <year>2011</year>
        <gdppc>13600</gdppc>
        <neighbor name="Costa Rica" direction="W"/>
        <neighbor name="Colombia" direction="E"/>
    </country>
</data>

You can do the following

>>> import xml.etree.ElementTree as ET
>>> tree = ET.parse('test.xml')
>>> for elem in tree.iter():
...     print elem
... 
<Element 'data' at 0x10b2d7b50>
<Element 'country' at 0x10b2d7b90>
<Element 'rank' at 0x10b2d7bd0>
<Element 'year' at 0x10b2d7c50>
<Element 'gdppc' at 0x10b2d7d10>
<Element 'neighbor' at 0x10b2d7e90>
<Element 'neighbor' at 0x10b2d7ed0>
<Element 'country' at 0x10b2d7f10>
<Element 'rank' at 0x10b2d7f50>
<Element 'year' at 0x10b2d7f90>
<Element 'gdppc' at 0x10b2d7fd0>
<Element 'neighbor' at 0x10b2db050>
<Element 'country' at 0x10b2db090>
<Element 'rank' at 0x10b2db0d0>
<Element 'year' at 0x10b2db110>
<Element 'gdppc' at 0x10b2db150>
<Element 'neighbor' at 0x10b2db190>
<Element 'neighbor' at 0x10b2db1d0>
2 of 7
22

Adding to Robert Christie's answer it is possible to iterate over all nodes using fromstring() by converting the Element to an ElementTree:

import xml.etree.ElementTree as ET

e = ET.ElementTree(ET.fromstring(xml_string))
for elt in e.iter():
    print "%s: '%s'" % (elt.tag, elt.text)
🌐
TutorialsPoint
tutorialspoint.com › how-to-get-specific-nodes-in-xml-file-in-python
How to get specific nodes in xml file in Python?
September 1, 2025 - When we are processing XML file, sometimes we need to extract all elements which have the same tag name such as all <title> tags in a file. This can be achieved using the iter() method in Python which helps in looping through all matching elements within the XML tree.
🌐
CopyProgramming
copyprogramming.com › howto › iterate-through-xml-child-of-child-tags-in-python-using-elementtree
Python: Traversing nested XML elements using ElementTree in Python
June 11, 2023 - Please note that the quantity of child nodes present within the <term> node could differ. This is only a sample XML and I am not focusing on any particular element of the table. ... The syntax for the builtin xml module is quite similar to that of beautifulsoup. Substituting path_to_xml with your designated xml file path is required. from xml.etree import cElementTree as ET xml_dat = ET.parse(path_to_xml).getroot() for term in xml_dat.iter('term'): broaders = term.findall('broader') if ****(broaders) > 1: for broader in broaders: if term.find('id').text == broader.text: print(term.find('altLabel').find('value').text)
🌐
Read the Docs
python.readthedocs.io › en › latest › library › xml.etree.elementtree.html
20.5. xml.etree.ElementTree - Python Docs
November 15, 2017 - Where immediate feedback through events is wanted, calling method XMLPullParser.flush() can help reduce delay; please make sure to study the related security notes. Element has some useful methods that help iterate recursively over all the sub-tree below it (its children, their children, and so on).
🌐
WebScraping.AI
webscraping.ai › faq › lxml › what-is-the-correct-way-to-iterate-over-elements-in-an-lxml-tree
What is the correct way to iterate over elements in an lxml tree? | WebScraping.AI
May 22, 2017 - Learn multiple methods to iterate over lxml tree elements in Python: .iter(), XPath, direct children, and advanced filtering techniques.
🌐
Hackers and Slackers
hackersandslackers.com › xml-in-python
Working with XML tree data in Python
September 29, 2022 - We can loop through all occurrences of a n element name by using .iter().