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.
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.
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.
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:
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.
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.
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.fromstringwhen 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
- Python ZeroMQ connecting two different clients together in a ROUTER and a REP configuration
- Python ZeroMQ PUSH/PULL logic, set high water mark to a low end puller without losing any message
- Pythonic way to avoid if x return x statements
- Pythonic way to check if a file exists?
- Pythonic way to check if a list is sorted or not
- Pythonic way to check if a list is sorted or not
- Pythonic way to combine datetime.date and datetime.time objects
- Pythonic way to combine for-loop and if-statement
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack 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.