1

I have the following code that works and gives me the expected output.

#!/bin/env python
import xml.etree.ElementTree as e
tree = e.parse("Document.XML")
root = tree.getroot()
vals=[]

Can the following part of the code be a one-liner or any more compact ?

for ch in root.findall('arch'):
    for gc in ch.findall('pro'):
        vals.append(gc.get('label'))

The libxml2 version I have, doesn't support xpath, please don't suggest that option. The XMl file looks like this:

<projects>
  <arch name="arch1">
    <pro label="A1" type="B1" state="C1"/>
    ....
  </arch>
  ....
</projects>
1
  • 11
    Yes, you could, but I would advise against it. There's nothing unreadable about this code. Commented Aug 22, 2013 at 22:30

2 Answers 2

6

Sure, use a list comprehension with two loops:

vals = [gc.get('label') for ch in root.findall('arch') for gc in ch.findall('pro')]
Sign up to request clarification or add additional context in comments.

1 Comment

Or, of course, you could go half-way there with an explicit outer loop, but the inner loop replaced by the simple comprehension vals.append(gc.get('label') for gc in ch.findall('pro')). It's probably worth typing all three up and seeing which one is most readable to you (and your coworkers/fellow contributors/etc., if relevant).
1

Using xmltodict you can probably just do something like

data = xmltodict.parse("Document.XML")
val = data['arch']['pro']['@label']

You'll have to play with my pseudocode to add the list comprehension for multiple vals, but the above should illustrate the basic usage (and see the git page). Bruno Rocha recently blogged about xmltodict.

2 Comments

How do I get the xmltodict module ? Is this available in pyton 2.x ?
pip install xmltodict

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.