VOOZH about

URL: https://www.geeksforgeeks.org/python/how-to-parse-xml-and-count-instances-of-a-particular-node-attribute-in-python/

⇱ How to parse XML and count instances of a particular node attribute in Python? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to parse XML and count instances of a particular node attribute in Python?

Last Updated : 23 Jul, 2025

In this article, we will see how to parse XML and count instances of a particular node attribute in Python.

What is XML?

Extensible Markup Language (XML) Extensible Markup Language (XML) is a markup language that defines a set of rules for encoding documents in a format that is both human-readable and machine-readable. It is a markup language like HTML, and It is designed to store and transport data. Here, we will use built-in XML modules in python for parsing XML and then counting the instances of a node. We use ElementTree XML API and minidom APIto parse our XML file.

XML code for a note is given below:

It should be saved as a country_data.xml file in the same directory.

Example 1: 

In this example, We will use xml.etree.ElementTree module for parsing our XML file and storing in tree variable and after that we will find all the instances of a particular node attribute with the python findall() function of this module. Now we iterate over a list and check for a particular node attribute value if it matches then we will increment count as 1 to our variable.

Output:

total instance of given node attribute is : 1

Example 2:

In this example, we will parse our XML file with the help of minidom module and assign this to the doc variable, getElementsByTagName() function returns a list of instances of a particular node. Now we iterate over a list and check for a particular node attribute value if it matches then we will increment count as 1 to our variable.

Output:

Total instance of Particular node attribute is : 2
Comment
Article Tags:
Article Tags: