Explore Courses Blog Tutorials Interview Questions
0 votes
in Python by (16.4k points)

I have numerous rows in a database that contains XML and I'm attempting to compose Python code to count instances of a specific node attribute. 

My tree resembles: 



      <type foobar="1"/>

      <type foobar="2"/>



How might I access the attributes "1" and "2" in the XML utilizing Python?

1 Answer

0 votes
by (26.4k points)

I propose ElementTree. There are other viable executions of similar API, for example, lxml, and cElementTree in the Python standard library itself; however, in this unique circumstance, what they predominantly add is much more speed - the simplicity of programming part relies upon the API, which ElementTree characterizes. 

First form an Element case root from the XML, for example with the XML work, or by parsing a document with something like:

import xml.etree.ElementTree as ET

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

You can also do like this:

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

    value = type_tag.get('foobar')


Looking for a good python tutorial course? Join the python certification course and get certified.

For more details, do check out the below video tutorial...

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Browse Categories