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,910 points
609 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,910 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,880 points
311 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
391 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
960 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,090 points
733 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,058 views
0 votes
1 answer
0 votes
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
• 580 points
276,645 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
133,552 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