0

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?

2 Answers 2

1

you can find all elements of root:

for e in tree.findall('.//'):
    <do stuff>
Sign up to request clarification or add additional context in comments.

2 Comments

That's what i need! Thank you!
But this doesn't give the root element itself. This works better for e in tree.iter(): <do stuff>
0

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))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.