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'
Answer from Ryan Ginstrom on Stack Overflow 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'
Is XML difficult to learn?
No. Really there is not much to learn about it. It is just a data format. More on reddit.com
reading xml with python3
The xml is gzip compressed - requests handles this automatically for you which you could use instead of urllib.
response = requests.get(url)
tree = etree.fromstring(response.content)
http://stackoverflow.com/a/26435241 discusses solutions for doing it with urllib
More on reddit.comHow would I parse XML that I get through Pycurl?
Parsing any html or xml is easiest with BeautifulSoup. Just remember to specify that's it's XML, or it will default to HTML:
soup = bs4.BeautifulSoup(body, 'xml')More on reddit.com
Reading and writing out an XML file as flat file?
You probably want to write a SAX parser. Look at xml.sax in the stdlib.
More on reddit.comVideos
38:58
Python XML Parsing Tutorial Read And Write XML Files In Python ...
Parse XML Files with Python - Basics in 10 Minutes
17:34
Full XML Processing Guide in Python - YouTube
XML & ElementTree || Python Tutorial || Learn Python Programming ...
28:25
Parsing XML with Python (DevNet) - YouTube
18:33
Python Tutorial | Read XML using python | python xml parsing - YouTube
GeeksforGeeks
geeksforgeeks.org › python › reading-and-writing-xml-files-in-python
Reading and Writing XML Files in Python - GeeksforGeeks
January 12, 2026 - from bs4 import BeautifulSoup with open('dict.xml', 'r') as f: data = f.read() bs_data = BeautifulSoup(data, 'xml') for tag in bs_data.find_all('child', {'name':'Frank'}): tag['test'] = "WHAT !!" print(bs_data.prettify()) ... ElementTree is included in Python’s standard library, so no installation is required.
DataCamp
datacamp.com › tutorial › python-xml-elementtree
Python XML Tutorial: Element Tree Parse & Read | DataCamp
December 10, 2024 - Learn how you can parse, explore, modify and populate XML files with the Python ElementTree package, for loops and XPath expressions. ... Get your team access to the full DataCamp for business platform. Run and edit the code from this tutorial onlineRun code · As a data scientist, you'll find that understanding XML is powerful for both web-scraping and general practice in parsing a structured document.
Tutorialspoint
tutorialspoint.com › home › python › python xml processing
Python XML Processing
February 21, 2009 - The 'Element' class represents a single node in this tree. Reading and writing operations on XML files are done on the ElementTree level. Interactions with a single XML element and its sub-elements are done on the Element level.
Zyte
zyte.com › learn › a-practical-guide-to-xml-parsing-with-python
A Practical Guide to Python XML Parsing
Whether you're dealing with configuration files, SOAP-based APIs, or large datasets used in enterprise applications, understanding how to parse and manipulate XML is essential. In this guide, we’ll dive into the world of XML parsing using · Python, providing not just basic methods but also advanced techniques like handling XML namespaces, performing XPath queries, and mapping XML data to custom Python objects.
LearnPython.com
learnpython.com › blog › read-xml-into-python
How to Read XML Files into Python | LearnPython.com
Now that we've grasped the basics of XML, let's delve into how we can efficiently read XML files into Python for further analysis and processing. 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.
ScrapingAnt
scrapingant.com › blog › python-parse-xml
How to Parse XML in Python | ScrapingAnt
August 2, 2024 - These built-in Python XML parsers offer a good balance of speed and ease of use for most applications. ... Consider using lxml, a fast and feature-rich Python library that combines the power of libxml2 and libxslt (lxml documentation). lxml is particularly efficient for parsing large XML documents and provides additional functionality like XPath support. ... Utilize event-driven parsing with xml.parsers.expat or lxml.etree.iterparse() to process XML data without loading the entire document into memory (xml.parsers.expat documentation).
GitHub
github.com › oxylabs › how-to-parse-xml-in-python
GitHub - oxylabs/how-to-parse-xml-in-python: Follow this in-depth technical tutorial to learn how to parse XML data in Python, what libraries you should use, how to handle invalid XML, and more. · GitHub
It has several key steps such as checking the syntax of the XML document, tokenizing, and building the document structure in a hierarchy. XML parsing is surprisingly difficult if you've worked with any XML document before, then you might already ...
Author oxylabs
Oxylabs
oxylabs.io › blog › python-parse-xml
How to Parse XML in Python
Then, we’re iterating over all the child nodes and storing the data in a `dict` object. You can use the `untangle` library to convert XML files directly to a Python dictionary object. ... The cool thing about this library is you can pass a URL, filename, or even an XML string to the `parse,` and it’ll still work.
Rdegges
rdegges.com › 2013 › quickly-extract-xml-data-with-python
Randall Degges - Quickly Extract XML Data with Python
We then use the find method, passing in an XPath selector, which allows us to specify what element we’re trying to extract. If the element can’t be found, None is returned. If the element can be found, then we’ll use the .text property on our element object to grab the data out of the desired XML element.
freeCodeCamp
freecodecamp.org › news › how-to-parse-xml-in-python-without-using-external-libraries
How to Parse XML in Python Without Using External Libraries
November 12, 2025 - We convert numeric strings to proper types (float for price, int for stock) For nested categories, we first check if the <categories> element exists. Then we iterate through child <category> elements and collect their text · The result is clean Python data structures you can easily work with. You can now use the parser like so: products = parse_product_catalog('products.xml') for product in products: print(f"\nProduct: {product['name']}") print(f" ID: {product['id']}") print(f" Price: {product['currency']} {product['price']}") print(f" Stock: {product['stock']}") print(f" Categories: {', '.join(product['categories'])}")