Python
XML
ElementTree
String Parsing
XML Parsing

Python xml ElementTree from a string source?

Interview Questions practice on Codemia

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

Browse interview questions

Introduction

If XML arrives from an API response, a message queue, or a test fixture, you do not need to save it to a file before parsing it. Python's xml.etree.ElementTree module can parse XML directly from a string using fromstring, which gives you the root element immediately.

Parse XML with ET.fromstring

The standard entry point for string input is ElementTree.fromstring.

python
1import xml.etree.ElementTree as ET
2
3xml_data = """
4<catalog>
5    <book id="101">
6        <title>Clean Code</title>
7        <author>Robert C. Martin</author>
8    </book>
9    <book id="102">
10        <title>Designing Data-Intensive Applications</title>
11        <author>Martin Kleppmann</author>
12    </book>
13</catalog>
14"""
15
16root = ET.fromstring(xml_data)
17print(root.tag)

root is now an Element instance representing the top node of the parsed tree. From there you can inspect tags, attributes, text, and child elements.

Read Child Elements and Attributes

Once you have the root element, use find, findall, and .attrib to navigate the tree.

python
1for book in root.findall("book"):
2    book_id = book.attrib["id"]
3    title = book.findtext("title")
4    author = book.findtext("author")
5    print(book_id, title, author)

This pattern is common when XML has a predictable structure. findtext is convenient because it returns the text content directly instead of the element object.

If you only need one element, find works well:

python
first_book = root.find("book")
if first_book is not None:
    print(first_book.findtext("title"))

Modify the Tree and Serialize It Again

ElementTree is not only for reading. You can edit the parsed tree and turn it back into XML.

python
1new_book = ET.SubElement(root, "book", id="103")
2ET.SubElement(new_book, "title").text = "Refactoring"
3ET.SubElement(new_book, "author").text = "Martin Fowler"
4
5xml_output = ET.tostring(root, encoding="unicode")
6print(xml_output)

This is useful for tests, lightweight XML transformations, and preparing a payload for another system.

Be Careful with Namespaces

Parsing a plain XML string is easy. Parsing namespaced XML requires more attention because the visible tag names in the document may map to fully qualified names internally.

python
1import xml.etree.ElementTree as ET
2
3xml_data = """
4<feed xmlns="http://example.com/feed">
5    <entry>
6        <title>Hello</title>
7    </entry>
8</feed>
9"""
10
11root = ET.fromstring(xml_data)
12ns = {"f": "http://example.com/feed"}
13
14entry = root.find("f:entry", ns)
15if entry is not None:
16    print(entry.findtext("f:title", namespaces=ns))

If find returns None unexpectedly, namespaces are one of the first things to check.

Common Pitfalls

The most common mistake is calling ET.parse on raw XML text. parse expects a file path or file-like object, not a plain XML string. For in-memory XML text, use fromstring.

Another issue is assuming every child exists. find can return None, so direct chaining without checks can raise an exception when the input is missing a field or when the tag name is slightly different than expected.

Malformed XML is another source of confusion. A missing closing tag, invalid character, or broken namespace declaration raises xml.etree.ElementTree.ParseError. Wrap parsing in a try block if the input comes from an unreliable source.

Finally, remember that XML text and tail text are distinct concepts in ElementTree. If formatting or mixed content matters, inspect both .text and .tail instead of assuming everything lives in a simple tag value.

If you are validating data from an external service, print or log the failing payload during debugging. Many "ElementTree problems" turn out to be truncated responses, HTML error pages, or XML encoded differently than the application expected.

Summary

  • Use xml.etree.ElementTree.fromstring when your XML source is already in memory as a string.
  • Navigate the tree with find, findall, findtext, and element attributes.
  • Modify elements in place and serialize them again with ET.tostring.
  • Check namespaces when straightforward tag lookups unexpectedly fail.
  • Expect parse errors and missing elements when working with external XML data.

Related reading
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

All Rights Reserved.