Nesless
Nesless

Reputation: 43

How to print all tags and text within these tags using xml.etree.ElementTree?

I am learning how to get information from xml file and hope you can help me with this simple question.

I want to recieve all the information from the xml file. F.e here is a xml file: https://msdn.microsoft.com/en-us/library/ms762271%28v=vs.85%29.aspx

That's my code:

import urllib
import xml.etree.ElementTree as ET

x = open('books.xml')
tree = ET.parse(x)
root = tree.getroot()
print root.tag

for c in root:
    print c.tag,":", c.text
    for x in c:
        print x.tag,":", x.text

Is there more elegant way to print all informtaion which is located in the file?

Upvotes: 0

Views: 7945

Answers (2)

Nuncjo
Nuncjo

Reputation: 1340

Do you mean more elegant output or more elegant way to iterate the tree ? If you mean second option then maybe You should try list comprehension ?

import xml.etree.ElementTree as ET
from pprint import pprint

x = open('books.xml')
tree = ET.parse(x)
root = tree.getroot()

d = [{x.tag: x.text for x in c} for c in root]
pprint(d)

You could also do this:

def recursive_dict(element):
    return element.tag, dict(map(recursive_dict, element)) or element.text

for book in root:
    pprint(recursive_dict(root))

Upvotes: 0

postelrich
postelrich

Reputation: 3506

you can find all elements of root:

for e in tree.findall('.//'):
    <do stuff>

Upvotes: 1

Related Questions