Back

Explore Courses Blog Tutorials Interview Questions
0 votes
4 views
in Python by (47.6k points)

I have many rows in a database that contains XML and I'm trying to write a Python script that will go through those rows and count how many instances of a particular node attribute show up. For instance, my tree looks like:

<foo>

    <bar> 

        <type foobar="1"/> 

        <type foobar="2"/> 

    </bar>

</foo>

How can I access the attributes 1 and 2 in the XML using Python?

1 Answer

0 votes
by (106k points)

Well we have various ways to parse XML in Python but the best way to use is minidom() but before using minidom() you need to know how to use DOM(Document Object Model) which is the quickest and pretty straight forward:-

minidom():-

The xml.dom.minidom is a minimal implementation of the Document Object Model interface, with an API similar to that in other languages. It is intended to be simpler than the full DOM and also significantly smaller. 

Below is the Python code that parses your XML code into Python:-

from xml.dom import minidom

xmldoc = minidom.parse('items.xml') 

itemlist = xmldoc.getElementsByTagName('item') print(len(itemlist))

print(itemlist[0].attributes['name'].value) 

for s in itemlist: 

     print(s.attributes['name'].value)

If you do not want to use minidom() then you can use ElementTree which does not require DOM knowledge.

To use ElementTree firstly you will have to build an Element instance root from the XML by parsing a file by the following way:

import xml.etree.ElementTree as ET

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

The above code will parse the root from XML then you will use the below-mentioned code:-

for type_tag in root.findall('bar/type'): 

         value = type_tag.get('foobar') 

         print(value)

Related questions

0 votes
1 answer
asked Dec 18, 2020 in Python by laddulakshana (16.4k points)
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Apr 14, 2021 in Java by Jake (7k points)

Browse Categories

...