Categories
Python Answers

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

Spread the love

Sometimes, we want to parse XML and count instances of a particular node attribute with Python.

In this article, we’ll look at how to parse XML and count instances of a particular node attribute with Python.

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

To parse XML and count instances of a particular node attribute with Python, we can use the xml.etree.ElementTree constructor.

For instance, we write:

file.xml

<foo>
   <bar>
      <type foobar="1"/>
      <type foobar="2"/>
   </bar>
</foo>

to define an XML file with some content.

Then we write:

main.py:

import xml.etree.ElementTree as ET

root = ET.parse('file.xml').getroot()

for type_tag in root.findall('bar/type'):
    value = type_tag.get('foobar')
    print(value)

to import the xml.etree.ElementTree constructor as ET.

Then we use the ET constructor with the XML file path.

Next, we call getRoot to get the root node of the XML file.

Then we call findall with the node tag path we’re looking for.

We then loop through the returned nodes with a for loop.

And then we call get with the attribute name string of the attribute we want to get.

This returns the attribute value and we assign that to value and print it.

Therefore, we see:

1
2

printed.

Conclusion

To parse XML and count instances of a particular node attribute with Python, we can use the xml.etree.ElementTree constructor.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *