Python XML iterate child nodes

James 19 Published: 11/03/2024

Python XML iterate child nodes

I'd be happy to help you with that.

Python provides several ways to iterate over the child elements of an XML node using the xml.etree.ElementTree module. Here are a few examples:

Using find and a list comprehension:
import xml.etree.ElementTree as ET
Load XML file

tree = ET.parse("your_xml_file.xml")

root = tree.getroot()

Find all child elements of root element

child_nodes = [node for node in root.findall("*")]

Print each child node's tag and text content

for node in child_nodes:

print(f"{node.tag}: {node.text}")

In this example, findall("*") returns a list of all child elements of the root element. We then use a list comprehension to create a new list containing only these child elements. Finally, we iterate over each child node and print its tag (e.g., "name", "age", etc.) and text content.

Using iter:
import xml.etree.ElementTree as ET
Load XML file

tree = ET.parse("your_xml_file.xml")

root = tree.getroot()

Iterate over child elements of root element using iter()

for node in root.iter():

print(f"{node.tag}: {node.text}")

In this example, iter() returns an iterator that yields each child element of the root element. We then iterate over this iterator and print each child node's tag and text content.

Using a recursive function:
import xml.etree.ElementTree as ET

def traverse_xml(node):

if node is None:

return

Print current node's tag and text content

print(f"{node.tag}: {node.text}")

Recursively traverse child elements

for child in node:

traverse_xml(child)

Load XML file

tree = ET.parse("your_xml_file.xml")

root = tree.getroot()

Start traversing from root element

traverse_xml(root)

In this example, we define a recursive function traverse_xml that takes an XML node as input. The function prints the current node's tag and text content, then recursively calls itself for each child element.

These are just a few ways to iterate over child elements in Python using the xml.etree.ElementTree module. You can choose the method that best fits your specific use case.

How to do XML parsing using Python?

XML (Extensible Markup Language) is a markup language that defines a set of rules for encoding documents in a format that is both human-readable and machine-readable. In Python, you can parse XML files or strings using the xml.etree.ElementTree module.

Here's an example of how to use this module:

import xml.etree.ElementTree as ET
Parse an XML file

tree = ET.parse('example.xml')

root = tree.getroot()

Find all elements with tag 'person'

for person in root.findall('.//person'):

print(f"Name: {person.find('name').text}, Age: {person.find('age').text}")

In this example, we first import the xml.etree.ElementTree module. Then, we use the parse() function to parse an XML file called 'example.xml'. The parsed tree is stored in the tree variable.

Next, we get a reference to the root element of the XML document using the getroot() method. Then, we find all elements with the tag 'person' (regardless of their location within the document) using the findall() method.

For each 'person' element found, we print out their name and age. This is done by finding the 'name' and 'age' sub-elements of each 'person' element, then accessing the text content of these elements using the .text property.

You can also create new XML files or strings from Python data structures:

import xml.etree.ElementTree as ET

root = ET.Element('root')

child1 = ET.SubElement(root, 'child1', attrib={'id': 1})

child2 = ET.SubElement(child1, 'grandchild')

root.set('attr', 'value')

tree = ET.ElementTree(root)

tree.write('output.xml')

In this example, we create a new XML tree from scratch. We start by creating the root element, then add child elements and sub-elements to it using the Element and Subelement classes.

Finally, we set an attribute on the root element using the .set() method, then write the entire XML tree to a file called 'output.xml' using the write() method.

Python's xml.etree.ElementTree module is quite powerful, and it can handle many common XML parsing tasks. However, if you need more advanced features or customization options, you might want to consider using a third-party library like lxml or xmltodict.