0 votes
1 view
in Python by (47.8k 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 (107k 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
0 votes
1 answer
asked Jul 3, 2019 in Python by Sammy (47.8k points)
0 votes
1 answer
0 votes
1 answer
asked Jul 5, 2019 in Python by Sammy (47.8k points)
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...