5

I have an XML file which has a lot of different nodes with the same attribute.

I was wondering if it's possible to find all these nodes using Python and any additional package like minidom or ElementTree.

1
  • thanks guys, i was using minidom and seems like it's not so powerful, will move to ElementTree finally. Commented Jan 7, 2015 at 3:30

2 Answers 2

9

You can use built-in xml.etree.ElementTree module.

If you want all elements that have a particular attribute regardless of the attribute values, you can use an xpath expression:

//tag[@attr]

Or, if you care about values:

//tag[@attr="value"]

Example (using findall() method):

import xml.etree.ElementTree as ET

data = """
<parent>
    <child attr="test">1</child>
    <child attr="something else">2</child>
    <child other_attr="other">3</child>
    <child>4</child>
    <child attr="test">5</child>
</parent>
"""

parent = ET.fromstring(data)
print [child.text for child in parent.findall('.//child[@attr]')]
print [child.text for child in parent.findall('.//child[@attr="test"]')]

Prints:

['1', '2', '5']
['1', '5']
Sign up to request clarification or add additional context in comments.

3 Comments

Why assume that all of these nodes are going to be direct children of the root element? What about if the children and grandchildren, or descendants at any level of nesting, have these attributes? parent.findall('.//[@attr]') throws an invalid descendant error in Python 2.7.
@alex wait, // or .// would look for node at any level of nesting. Or, I misunderstood your question..thanks.
@alex ah, if you mean to look for any node name, use .//*[@attr].
2

This is a good sample/start script using :

# -*- coding: utf-8 -*-
from lxml import etree
fp = open("xml.xml")
tree = etree.parse(fp)
for el in tree.findall('//node[@attr="something"]'):
    print(el.text)

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.