XML Parsing
Node Attribute
Coding
Programming
Data Extraction

How can I parse XML and get instances of a particular node attribute?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

If you need values from a specific XML attribute, the basic workflow is always the same: parse the document, select the nodes you care about, and read the attribute from each node. The exact API varies by language, but the conceptual steps do not.

A Small XML Example

Suppose the XML looks like this:

xml
1<books>
2  <book id="1" title="The Great Gatsby" />
3  <book id="2" title="1984" />
4  <book id="3" title="Dune" />
5</books>

If the goal is "get all title attributes from book nodes," then you do not need to traverse every node manually. You only need a query that targets book elements.

Python Example with ElementTree

Python's standard library makes this straightforward:

python
1import xml.etree.ElementTree as ET
2
3xml_data = """
4<books>
5  <book id="1" title="The Great Gatsby" />
6  <book id="2" title="1984" />
7  <book id="3" title="Dune" />
8</books>
9"""
10
11root = ET.fromstring(xml_data)
12
13titles = [book.get("title") for book in root.findall("book")]
14print(titles)

Output:

text
['The Great Gatsby', '1984', 'Dune']

The important parts are:

  • 'findall("book") selects the nodes'
  • 'get("title") reads the attribute from each node'

Java Example with DOM

In Java, the DOM API gives the same result:

java
1import java.io.ByteArrayInputStream;
2import javax.xml.parsers.DocumentBuilderFactory;
3import org.w3c.dom.Document;
4import org.w3c.dom.Element;
5import org.w3c.dom.NodeList;
6
7public class XmlAttributeExample {
8    public static void main(String[] args) throws Exception {
9        String xml = """
10            <books>
11              <book id="1" title="The Great Gatsby" />
12              <book id="2" title="1984" />
13              <book id="3" title="Dune" />
14            </books>
15            """;
16
17        Document doc = DocumentBuilderFactory.newInstance()
18            .newDocumentBuilder()
19            .parse(new ByteArrayInputStream(xml.getBytes()));
20
21        NodeList books = doc.getElementsByTagName("book");
22        for (int i = 0; i < books.getLength(); i++) {
23            Element book = (Element) books.item(i);
24            System.out.println(book.getAttribute("title"));
25        }
26    }
27}

Again, the work is selection plus attribute access.

For very large XML documents, a tree parser may use more memory than you want. In those cases, streaming approaches such as SAX or StAX can still read attributes efficiently, but they do it event by event instead of building the whole document tree first.

Filtering for One Particular Attribute Value

Sometimes you want nodes whose attribute matches a certain value. In Python:

python
1matching = [
2    book for book in root.findall("book")
3    if book.get("id") == "2"
4]
5
6for book in matching:
7    print(book.get("title"))

This gives you the nodes with id="2" and then lets you read any other attributes from them.

Namespaces Matter

XML namespaces are the most common source of confusion. If the document uses namespaced tags, a plain query like findall("book") may return nothing even though the nodes clearly exist.

In that case, you need namespace-aware queries. The data is still there; your selector is just incomplete.

So when the parser "finds nothing," inspect the XML root and check whether tag names are namespaced.

If the selection logic becomes more complex than simple tag scanning, an XPath-capable XML library may be a better fit because it lets you express attribute filters directly in the query.

Common Pitfalls

The biggest mistake is confusing node text with attributes. In XML, these are different storage locations. title="Dune" is an attribute, while Dune between opening and closing tags would be node text.

Another mistake is assuming every node has the attribute. Methods such as get("title") may return None or an empty string depending on the API and the XML content.

A third issue is ignoring namespaces. Many failed XML queries are really namespace mismatches, not parser bugs.

Summary

  • Parse the XML, select the relevant nodes, then read the attribute values.
  • In Python, findall plus get is often enough.
  • In Java DOM, use getElementsByTagName and getAttribute.
  • Distinguish carefully between attributes and inner text.
  • If queries return nothing unexpectedly, check for XML namespaces first.

Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions