🌐
Python
docs.python.org › 3 › library › xml.etree.elementtree.html
xml.etree.ElementTree — The ElementTree XML API
For the XML data ... the a element ... tail "3". To collect the inner text of an element, see itertext(), for example "".join(element.itertext())....
🌐
DataCamp
datacamp.com › tutorial › python-xml-elementtree
Python XML Tutorial: Element Tree Parse & Read | DataCamp
December 10, 2024 - Parse and read XML data with Element Tree Python package. Learn how to use xml.etree.elementtree and explore your data through XML today!
🌐
Real Python
realpython.com › ref › stdlib › xml
xml | Python Standard Library – Real Python
>>> import xml.etree.ElementTree as ET >>> root = ET.Element("data") >>> item = ET.SubElement(root, "item") >>> item.text = "Python" >>> tree = ET.ElementTree(root) >>> ET.dump(tree) <data><item>Python</item></data>
🌐
The Hitchhiker's Guide to Python
docs.python-guide.org › scenarios › xml
XML parsing — The Hitchhiker's Guide to Python
For example, an XML file like this: <?xml version="1.0"?> <root> <child name="child1"> </root> can be loaded like this: import untangle obj = untangle.parse('path/to/file.xml') and then you can get the child element’s name attribute like this: ...
🌐
Zyte
zyte.com › learn › a-practical-guide-to-xml-parsing-with-python
A Practical Guide to Python XML Parsing
Python provides convenient methods to change the content, attributes, and structure of an XML tree. You can modify the text content of any element in the XML tree: ... This snippet updates the text of all child elements to 'Updated Value'. Just like element text, attributes can also be modified dynamically: ... This example changes the id attribute of every <child> element to '2'.
🌐
Tutorialspoint
tutorialspoint.com › home › python › python xml processing
Python XML Processing
February 21, 2009 - Discover how to effectively process XML data in Python with practical examples and libraries.
🌐
Python Module of the Week
pymotw.com › 2 › xml › etree › ElementTree › create.html
Creating XML Documents - Python Module of the Week
The output contains only the XML nodes in the tree, not the XML declaration with version and encoding. $ python ElementTree_create.py <top><!--Generated for PyMOTW--><child>This child contains text.</ch ild><child_with_tail>This child has regular text.</child_with_tail>A nd "tail" text.<child_with_entity_ref>This &amp; that</child_with_en tity_ref></top>
🌐
Python
docs.python.org › 3 › library › xml.html
XML Processing Modules — Python 3.14.3 documentation
Source code: Lib/xml/ Python’s interfaces for processing XML are grouped in the xml package. It is important to note that modules in the xml package require that there be at least one SAX-compliant...
Find elsewhere
🌐
Real Python
realpython.com › python-xml-parser
A Roadmap to XML Parsers in Python – Real Python
September 25, 2023 - It’s somewhat limited compared to the DOM but should be enough to implement a basic XML streaming push parser without resorting to third-party libraries. With this in mind, there’s a less verbose pull parser available in Python, which you’ll explore next. ... The parsers in the Python standard library often work together. For example, the xml.dom.pulldom module wraps the parser from xml.sax to take advantage of buffering and read the document in chunks.
🌐
Edureka
edureka.co › blog › python-xml-parser-tutorial
Python XML Parser Tutorial | ElementTree and Minidom Parsing | Edureka
December 5, 2024 - EXAMPLE: ... OUTPUT: Idly Paper Dosa Upma Bisi Bele Bath Kesari Bath To calculate the number of items on our menu, you can make use of the len() function as follows: ... The output specifies that our menu consists of 5 items. This brings us to the end of this Python XML Parser Tutorial.
Top answer
1 of 9
19

lxml has been mentioned. You might also check out lxml.objectify for some really simple manipulation.

>>> from lxml import objectify
>>> tree = objectify.fromstring(your_xml)
>>> tree.weather.attrib["module_id"]
'0'
>>> tree.weather.forecast_information.city.attrib["data"]
'Mountain View, CA'
>>> tree.weather.forecast_information.postal_code.attrib["data"]
'94043'
2 of 9
10

You want a thin veneer? That's easy to cook up. Try the following trivial wrapper around ElementTree as a start:

# geetree.py
import xml.etree.ElementTree as ET

class GeeElem(object):
    """Wrapper around an ElementTree element. a['foo'] gets the
       attribute foo, a.foo gets the first subelement foo."""
    def __init__(self, elem):
        self.etElem = elem

    def __getitem__(self, name):
        res = self._getattr(name)
        if res is None:
            raise AttributeError, "No attribute named '%s'" % name
        return res

    def __getattr__(self, name):
        res = self._getelem(name)
        if res is None:
            raise IndexError, "No element named '%s'" % name
        return res

    def _getelem(self, name):
        res = self.etElem.find(name)
        if res is None:
            return None
        return GeeElem(res)

    def _getattr(self, name):
        return self.etElem.get(name)

class GeeTree(object):
    "Wrapper around an ElementTree."
    def __init__(self, fname):
        self.doc = ET.parse(fname)

    def __getattr__(self, name):
        if self.doc.getroot().tag != name:
            raise IndexError, "No element named '%s'" % name
        return GeeElem(self.doc.getroot())

    def getroot(self):
        return self.doc.getroot()

You invoke it so:

>>> import geetree
>>> t = geetree.GeeTree('foo.xml')
>>> t.xml_api_reply.weather.forecast_information.city['data']
'Mountain View, CA'
>>> t.xml_api_reply.weather.current_conditions.temp_f['data']
'68'
🌐
GeeksforGeeks
geeksforgeeks.org › python › xml-parsing-python
XML parsing in Python - GeeksforGeeks
June 28, 2022 - For more insight on how requests module works, follow this article: GET and POST requests using Python · Parsing XML We have created parseXML() function to parse XML file. We know that XML is an inherently hierarchical data format, and the most natural way to represent it is with a tree. Look at the image below for example: Here, we are using xml.etree.ElementTree (call it ET, in short) module.
Top answer
1 of 6
424

These days, the most popular (and very simple) option is the ElementTree API, which has been included in the standard library since Python 2.5.

The available options for that are:

  • ElementTree (Basic, pure-Python implementation of ElementTree. Part of the standard library since 2.5)
  • cElementTree (Optimized C implementation of ElementTree. Also offered in the standard library since 2.5. Deprecated and folded into the regular ElementTree as an automatic thing as of 3.3.)
  • LXML (Based on libxml2. Offers a rich superset of the ElementTree API as well XPath, CSS Selectors, and more)

Here's an example of how to generate your example document using the in-stdlib cElementTree:

import xml.etree.cElementTree as ET

root = ET.Element("root")
doc = ET.SubElement(root, "doc")

ET.SubElement(doc, "field1", name="blah").text = "some value1"
ET.SubElement(doc, "field2", name="asdfasd").text = "some vlaue2"

tree = ET.ElementTree(root)
tree.write("filename.xml")

I've tested it and it works, but I'm assuming whitespace isn't significant. If you need "prettyprint" indentation, let me know and I'll look up how to do that. (It may be an LXML-specific option. I don't use the stdlib implementation much)

For further reading, here are some useful links:

  • API docs for the implementation in the Python standard library
  • Introductory Tutorial (From the original author's site)
  • LXML etree tutorial. (With example code for loading the best available option from all major ElementTree implementations)

As a final note, either cElementTree or LXML should be fast enough for all your needs (both are optimized C code), but in the event you're in a situation where you need to squeeze out every last bit of performance, the benchmarks on the LXML site indicate that:

  • LXML clearly wins for serializing (generating) XML
  • As a side-effect of implementing proper parent traversal, LXML is a bit slower than cElementTree for parsing.
2 of 6
79

The lxml library includes a very convenient syntax for XML generation, called the E-factory. Here's how I'd make the example you give:

#!/usr/bin/python
import lxml.etree
import lxml.builder    

E = lxml.builder.ElementMaker()
ROOT = E.root
DOC = E.doc
FIELD1 = E.field1
FIELD2 = E.field2

the_doc = ROOT(
        DOC(
            FIELD1('some value1', name='blah'),
            FIELD2('some value2', name='asdfasd'),
            )   
        )   

print lxml.etree.tostring(the_doc, pretty_print=True)

Output:

<root>
  <doc>
    <field1 name="blah">some value1</field1>
    <field2 name="asdfasd">some value2</field2>
  </doc>
</root>

It also supports adding to an already-made node, e.g. after the above you could say

the_doc.append(FIELD2('another value again', name='hithere'))
🌐
LearnPython.com
learnpython.com › blog › read-xml-into-python
How to Read XML Files into Python | LearnPython.com
We have a couple different options for libraries when working with XML in Python. In this section, we'll explore how to read XML files in Python using both built-in and third-party libraries. We’ll compare their approaches and functionalities. In every example, we will use the books.xml file, whose content is laid out below:
🌐
Bright Data
brightdata.com › blog › how-tos › parsing-xml-in-python
How to Parse XML in Python? Multiple Methods Covered
September 16, 2025 - The ElementTree XML API provides a simple and intuitive API for parsing and creating XML data in Python. It’s a built-in module in Python’s standard library, which means you don’t need to install anything explicitly. For example, you can use the findall() method to find all the url elements from the root and print the text value of the loc element, like this:
Top answer
1 of 2
49

So I have ElementTree 1.2.6 on my box now, and ran the following code against the XML chunk you posted:

import elementtree.ElementTree as ET

tree = ET.parse("test.xml")
doc = tree.getroot()
thingy = doc.find('timeSeries')

print thingy.attrib

and got the following back:

{'name': 'NWIS Time Series Instantaneous Values'}

It appears to have found the timeSeries element without needing to use numerical indices.

What would be useful now is knowing what you mean when you say "it doesn't work." Since it works for me given the same input, it is unlikely that ElementTree is broken in some obvious way. Update your question with any error messages, backtraces, or anything you can provide to help us help you.

2 of 2
22

If I understand your question correctly:

for elem in doc.findall('timeSeries/values/value'):
    print elem.get('dateTime'), elem.text

or if you prefer (and if there is only one occurrence of timeSeries/values:

values = doc.find('timeSeries/values')
for value in values:
    print value.get('dateTime'), elem.text

The findall() method returns a list of all matching elements, whereas find() returns only the first matching element. The first example loops over all the found elements, the second loops over the child elements of the values element, in this case leading to the same result.

I don't see where the problem with not finding timeSeries comes from however. Maybe you just forgot the getroot() call? (note that you don't really need it because you can work from the elementtree itself too, if you change the path expression to for example /timeSeriesResponse/timeSeries/values or //timeSeries/values)

🌐
ScrapingAnt
scrapingant.com › blog › python-parse-xml
How to Parse XML in Python | ScrapingAnt
August 2, 2024 - For secure XML parsing, consider using the defusedxml library (defusedxml documentation), which provides safe replacements for all of Python's standard library XML parsers: from defusedxml import ElementTree as ET # Parse the XML file safely tree = ET.parse('example.xml') # Get the root element root = tree.getroot()
🌐
Python 101
python101.pythonlibrary.org › chapter23_xml.html
Chapter 23 - The xml module — Python 101 1.0 documentation
This is fairly typical XML and actually pretty intuitive to read. There is some really nasty XML out in the wild that you may have to work with. Anyway, save the XML code above with the following name: appt.xml · Let’s spend some time getting acquainted with how to parse this file using Python’s minidom module.
🌐
Studytonight
studytonight.com › python-howtos › how-to-read-xml-file-in-python
How to read XML file in Python - Studytonight
In this example, we will use a Python library named BeautifulSoup. Beautiful Soup supports the HTML parser (lxml) included in Python’s standard library. Use the following command to install beautiful soup and lmxl parser in case, not installed. #for beautifulsoup pip install beautifulsoup4 #for lmxl parser pip install lxml · After successful installation, use these libraries in python code. We are using this XML file to read with Python code.