How do I parse XML in Python

0 votes

I have many rows in a database that contains XML and I'm trying to write a Python script to count instances of a particular node attribute.

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?

Nov 20, 2020 in Python by anonymous
• 8,870 points
798 views

1 answer to this question.

0 votes

First build an Element instance root from the XML, e.g. with the XML function, or by parsing a file with something like:

import xml.etree.ElementTree as ET
root = ET.parse('thefile.xml').getroot()

Or any of the many other ways shown at ElementTree. Then do something like:

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

And similar, usually pretty simple, code patterns.

answered Nov 20, 2020 by Gitika
• 65,770 points

Related Questions In Python

0 votes
1 answer

How do I parse XML in Python?

Hello @kartik, You can use BeautifulSoup: from bs4 import BeautifulSoup x="""<foo> ...READ MORE

answered Nov 19, 2020 in Python by Niroj
• 82,840 points
481 views
0 votes
0 answers

how do i perform XML parsing in python?

can you give me the python code ...READ MORE

Apr 10, 2019 in Python by Waseem
• 4,540 points
598 views
0 votes
2 answers

How do I copy a file in python?

copy a file in python  from shutil ...READ MORE

answered Mar 27, 2019 in Python by rajesh
• 1,270 points
1,302 views
0 votes
1 answer

How do I copy a file in python?

Use the shutil module. copyfile(src, dst) Copy the contents ...READ MORE

answered Jul 31, 2018 in Python by Priyaj
• 58,020 points
973 views
0 votes
2 answers
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,434 views
0 votes
1 answer
+1 vote
4 answers

How do I remove an element from a list by index in Python?

Delete the List and its element: We have ...READ MORE

answered Jun 7, 2020 in Python by sahil
• 500 points
280,720 views
+1 vote
4 answers

How do i resolve the "unexpected indent" error in python?

Look for the whitespaces which are not ...READ MORE

answered Aug 2, 2019 in Python by Mohammad
• 3,230 points
137,449 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP