| « Back to Search | Reader Mode | Switch to Full Retro Site View | Links: Stay in Reader | Retro Mode: ON | Original » |
However, using a DTD isn't enough to fix the problem if your document has a default namespace, which is the case for the sample SVG image. To address this, you can visit all elements recursively in Python, check whether they have the
Your custom
Now, you're getting the expected XML element corresponding to the Using an ID allows for finding at most one unique element, but you can also find a collection of similar elements by their tag name . Unlike the
Notice that Unfortunately, elements like
The first argument must be the XML namespace, which typically has the form of a domain name , while the second argument is the tag name. Notice that the namespace prefix is irrelevant! To search all namespaces, you can provide a wildcard character ( Note: To find the namespaces declared in your XML document, you can check out the root element's attributes. In theory, they could be declared on any element, but the top-level one is where you'd usually find them. Once you locate the element you're interested in, you may use it to walk over the tree. However, another jarring quirk with
The newline characters and leading indentation are captured as separate tree elements, which is what the specification requires. Some parsers let you ignore these, but not the Python one. What you can do, however, is collapse whitespace in such nodes manually: Language: Python
Note that you also have to
Elements expose a few helpful methods and properties to let you query their details: Language: Python
For instance, you can check an element's namespace, tag name, or attributes. If you ask for a missing attribute, then you'll get an empty string ( Dealing with namespaced attributes isn't much different. You just have to remember to prefix the attribute name accordingly or provide the domain name: Language: Python
Strangely enough, the wildcard character ( Since this tutorial is only about XML parsing, you'll need to check the As you can see, the
|
| Non-incremental | Incremental (Blocking) | Incremental (Non-blocking) | |
|---|---|---|---|
ET.parse() |
✔️ | ||
ET.fromstring() |
✔️ | ||
ET.iterparse() |
✔️ | ||
ET.XMLPullParser |
✔️ |
The non-incremental strategy loads up the entire document into memory in a DOM-like fashion . There are two appropriately named functions in the module that allow for parsing a file or a Python string with XML content:
Language: Python>>> import xml.etree.ElementTree as ET
>>> # Parse XML from a filename
>>> ET.parse("smiley.svg")
<xml.etree.ElementTree.ElementTree object at 0x7fa4c980a6a0>
>>> # Parse XML from a file object
>>> with open("smiley.svg") as file:
... ET.parse(file)
...
<xml.etree.ElementTree.ElementTree object at 0x7fa4c96df340>
>>> # Parse XML from a Python string
>>> ET.fromstring("""\
... <svg viewBox="-105 -100 210 270">
... <!-- More content goes here... -->
... </svg>
... """)
<Element 'svg' at 0x7fa4c987a1d0>
Parsing a file object or a filename with parse() returns an instance of the ET.ElementTree class, which represents the whole element hierarchy. On the other hand, parsing a string with fromstring() will return the specific root ET.Element .
Alternatively, you can read the XML document incrementally with a streaming pull parser , which yields a sequence of events and elements:
Language: Python>>> for event, element in ET.iterparse("smiley.svg"):
... print(event, element.tag)
...
end {http://www.inkscape.org/namespaces/inkscape}custom
end {http://www.w3.org/2000/svg}stop
end {http://www.w3.org/2000/svg}stop
end {http://www.w3.org/2000/svg}stop
end {http://www.w3.org/2000/svg}linearGradient
⋮
By default, iterparse() emits only the end events associated with the closing XML tag. However, you can subscribe to other events as well. You can find them with string constants such as "comment":
>>> import xml.etree.ElementTree as ET
>>> for event, element in ET.iterparse("smiley.svg", ["comment"]):
... print(element.text.strip())
...
Head
Eyes
Mouth
Here's a list of all the available event types:
start: Start of an elementend: End of an elementcomment: Comment elementpi: Processing instruction, as in XSL start-ns: Start of a namespaceend-ns: End of a namespaceThe downside of iterparse() is that it uses blocking calls to read the next chunk of data, which might be unsuitable for asynchronous code running on a single thread of execution. To alleviate that, you can look into XMLPullParser , which is a little bit more verbose:
import xml.etree.ElementTree as ET
async def receive_data(url):
"""Download chunks of bytes from the URL asynchronously."""
yield b"<svg "
yield b"viewBox=\"-105 -100 210 270\""
yield b"></svg>"
async def parse(url, events=None):
parser = ET.XMLPullParser(events)
async for chunk in receive_data(url):
parser.feed(chunk)
for event, element in parser.read_events():
yield event, element
This hypothetical example feeds the parser with chunks of XML that can arrive a few seconds apart. Once there's enough content, you can iterate over a sequence of events and elements buffered by the parser. This non-blocking incremental parsing strategy allows for a truly concurrent parsing of multiple XML documents on the fly while you download them.
Elements in the tree are mutable, iterable, and indexable sequences . They have a length corresponding to the number of their immediate children:
Language: Python>>> import xml.etree.ElementTree as ET
>>> tree = ET.parse("smiley.svg")
>>> root = tree.getroot()
>>> # The length of an element equals the number of its children.
>>> len(root)
5
>>> # The square brackets let you access a child by an index.
>>> root[1]
<Element '{http://www.w3.org/2000/svg}defs' at 0x7fe05d2e8860>
>>> root[2]
<Element '{http://www.w3.org/2000/svg}g' at 0x7fa4c9848400>
>>> # Elements are mutable. For example, you can swap their children.
>>> root[2], root[1] = root[1], root[2]
>>> # You can iterate over an element's children.
>>> for child in root:
... print(child.tag)
...
{http://www.inkscape.org/namespaces/inkscape}custom
{http://www.w3.org/2000/svg}g
{http://www.w3.org/2000/svg}defs
{http://www.w3.org/2000/svg}text
{http://www.w3.org/2000/svg}script
Tag names might be prefixed with an optional namespace enclosed in a pair of curly braces ({}). The default XML namespace appears there, too, when defined. Notice how the swap assignment in the highlighted line made the <g> element come before <defs>. This shows the mutable nature of the sequence.
Here are a few more element attributes and methods that are worth mentioning:
Language: Python>>> element = root[0]
>>> element.tag
'{http://www.inkscape.org/namespaces/inkscape}custom'
>>> element.text
'Some value'
>>> element.attrib
{'x': '42', '{http://www.inkscape.org/namespaces/inkscape}z': '555'}
>>> element.get("x")
'42'
One of the benefits of this API is how it uses Python's native data types. Above, it uses a Python dictionary for the element's attributes. In the previous modules, those were wrapped in less convenient adapters. Unlike the DOM, the ElementTree API doesn't expose methods or properties for walking over the tree in any direction, but there are a couple of better alternatives.
As you've seen before, instances of the Element class implement the sequence protocol , letting you iterate over their direct children with a loop:
>>> for child in root:
... print(child.tag)
...
{http://www.inkscape.org/namespaces/inkscape}custom
{http://www.w3.org/2000/svg}defs
{http://www.w3.org/2000/svg}g
{http://www.w3.org/2000/svg}text
{http://www.w3.org/2000/svg}script
You get the sequence of the root's immediate children. To go deeper into nested descendants, however, you'll have to call the .iter() method on the ancestor element:
>>> for descendant in root.iter():
... print(descendant.tag)
...
{http://www.w3.org/2000/svg}svg
{http://www.inkscape.org/namespaces/inkscape}custom
{http://www.w3.org/2000/svg}defs
{http://www.w3.org/2000/svg}linearGradient
{http://www.w3.org/2000/svg}stop
{http://www.w3.org/2000/svg}stop
{http://www.w3.org/2000/svg}stop
{http://www.w3.org/2000/svg}g
{http://www.w3.org/2000/svg}circle
{http://www.w3.org/2000/svg}ellipse
{http://www.w3.org/2000/svg}ellipse
{http://www.w3.org/2000/svg}path
{http://www.w3.org/2000/svg}text
{http://www.w3.org/2000/svg}script
The root element has only five children but thirteen descendants in total. It's also possible to narrow down the descendants by filtering only specific tag names using an optional tag argument:
>>> tag_name = "{http://www.w3.org/2000/svg}ellipse"
>>> for descendant in root.iter(tag_name):
... print(descendant)
...
<Element '{http://www.w3.org/2000/svg}ellipse' at 0x7f430baa03b0>
<Element '{http://www.w3.org/2000/svg}ellipse' at 0x7f430baa0450>
This time, you only got two <ellipse> elements. Remember to include the XML namespace , such as {http://www.w3.org/2000/svg}, in your tag name -- as long as it's been defined. Otherwise, if you only provide the tag name without the right namespace, you could end up with fewer or more descendant elements than initially anticipated.
Dealing with namespaces is more convenient when using .iterfind(), which accepts an optional mapping of prefixes to domain names. To indicate the default namespace , you can leave the key blank or assign an arbitrary prefix, which must be used in the tag name later:
>>> namespaces = {
... "": "http://www.w3.org/2000/svg",
... "custom": "http://www.w3.org/2000/svg"
... }
>>> for descendant in root.iterfind("g", namespaces):
... print(descendant)
...
<Element '{http://www.w3.org/2000/svg}g' at 0x7f430baa0270>
>>> for descendant in root.iterfind("custom:g", namespaces):
... print(descendant)
...
<Element '{http://www.w3.org/2000/svg}g' at 0x7f430baa0270>
The namespace mapping lets you refer to the same element with different prefixes. Surprisingly, if you try to find those nested <ellipse> elements like before, then .iterfind() won't return anything because it expects an XPath expression rather than a simple tag name:
>>> for descendant in root.iterfind("ellipse", namespaces):
... print(descendant)
...
>>> for descendant in root.iterfind("g/ellipse", namespaces):
... print(descendant)
...
<Element '{http://www.w3.org/2000/svg}ellipse' at 0x7f430baa03b0>
<Element '{http://www.w3.org/2000/svg}ellipse' at 0x7f430baa0450>
By coincidence, the string "g" happens to be a valid path relative to the current root element, which is why the function returned a non-empty result before. However, to find the ellipses nested one level deeper in the XML hierarchy, you need a more verbose path expression.
ElementTree has limited syntax support for the XPath mini-language , which you can use to query elements in XML, similar to CSS selectors in HTML. There are other methods that accept such an expression:
Language: Python>>> namespaces = {"": "http://www.w3.org/2000/svg"}
>>> root.iterfind("defs", namespaces)
<generator object prepare_child.<locals>.select at 0x7f430ba6d190>
>>> root.findall("defs", namespaces)
[<Element '{http://www.w3.org/2000/svg}defs' at 0x7f430ba09e00>]
>>> root.find("defs", namespaces)
<Element '{http://www.w3.org/2000/svg}defs' at 0x7f430ba09e00>
While .iterfind() yields matching elements lazily, .findall() returns a list, and .find() returns only the first matching element. Similarly, you can extract text enclosed between the opening and closing tags of elements using .findtext() or get the inner text of the entire document with .itertext():
>>> namespaces = {"i": "http://www.inkscape.org/namespaces/inkscape"}
>>> root.findtext("i:custom", namespaces=namespaces)
'Some value'
>>> for text in root.itertext():
... if text.strip() != "":
... print(text.strip())
...
Some value
Hello <svg>!
console.log("CDATA disables XML parsing: <svg>")
⋮
You look for text embedded in a specific XML element first, then everywhere in the whole document. Searching by text is a powerful feature of the ElementTree API. It's possible to replicate it using other built-in parsers, but at the cost of increased code complexity and less convenience.
The ElementTree API is probably the most intuitive one of them all. It's Pythonic, efficient, robust, and universal. Unless you have a specific reason to use DOM or SAX, this should be your default choice.
Remove adsOccasionally, reaching for the XML parsers in the standard library might feel like picking up a sledgehammer to crack a nut. At other times, it's the opposite, and you wish for a parser that could do much more. For example, you might want to validate XML against a schema or use advanced XPath expressions. In those situations, it's best to check out the external libraries available on PyPI .
Below, you'll find a selection of external libraries with varying degrees of complexity and sophistication.
untangle: Convert XML to a Python ObjectIf you're looking for a one-liner that could turn your XML document into a Python object, then look no further. While it hasn't been updated in a few years, the untangle library might soon become your favorite way of parsing XML in Python. There's only one function to remember, and it accepts a URL, a filename, a file object, or an XML string:
>>> import untangle
>>> # Parse XML from a URL
>>> untangle.parse("http://localhost:8000/smiley.svg")
Element(name = None, attributes = None, cdata = )
>>> # Parse XML from a filename
>>> untangle.parse("smiley.svg")
Element(name = None, attributes = None, cdata = )
>>> # Parse XML from a file object
>>> with open("smiley.svg") as file:
... untangle.parse(file)
...
Element(name = None, attributes = None, cdata = )
>>> # Parse XML from a Python string
>>> untangle.parse("""\
... <svg viewBox="-105 -100 210 270">
... <!-- More content goes here... -->
... </svg>
... """)
Element(name = None, attributes = None, cdata = )
In each case, it returns an instance of the Element class. You can use the dot operator to access its children and the square bracket syntax to get XML attributes or one of the child nodes by index. To get the document's root element, for example, you can access it as if it was the object's property. To get one of the element's XML attributes, you may pass its name as a dictionary key:
>>> import untangle
>>> document = untangle.parse("smiley.svg")
>>> document.svg
Element(name = svg, attributes = {'xmlns': ...}, ...)
>>> document.svg["viewBox"]
'-105 -100 210 270'
There are no function or method names to remember. Instead, each parsed object is unique, so you really need to know the underlying XML document's structure to traverse it with untangle.
To find out what the root element's name is, call dir() on the document:
>>> dir(document)
['svg']
This reveals the names of the element's immediate children. Note that untangle redefines the meaning of dir() for its parsed documents. Usually, you call this built-in function to inspect a class or a Python module. The default implementation would return a list of attribute names rather than the child elements of an XML document.
If there's more than one child with the given tag name, then you can iterate over them with a loop or refer to one by index:
Language: Python>>> dir(document.svg)
['defs', 'g', 'inkscape_custom', 'script', 'text']
>>> dir(document.svg.defs.linearGradient)
['stop', 'stop', 'stop']
>>> for stop in document.svg.defs.linearGradient.stop:
... print(stop)
...
Element <stop> with attributes {'offset': ...}, ...
Element <stop> with attributes {'offset': ...}, ...
Element <stop> with attributes {'offset': ...}, ...
>>> document.svg.defs.linearGradient.stop[1]
Element(name = stop, attributes = {'offset': ...}, ...)
You might have noticed that the <inkscape:custom> element was renamed to inkscape_custom. Unfortunately, the library can't handle XML namespaces well, so if that's something you need to rely on, then you must look elsewhere.
Because of the dot notation, element names in XML documents must be valid Python identifiers . If they're not, then untangle will automatically rewrite their names by replacing forbidden characters with an underscore:
>>> dir(untangle.parse("<com:company.web-app></com:company.web-app>"))
['com_company_web_app']
Children's tag names aren't the only object properties you can access. Elements have a few predefined object attributes that might be shown by calling vars():
>>> element = document.svg.text
>>> list(vars(element).keys())
['_name', '_attributes', 'children', 'is_root', 'cdata']
>>> element._name
'text'
>>> element._attributes
{'x': '-40', 'y': '75'}
>>> element.children
[]
>>> element.is_root
False
>>> element.cdata
'Hello <svg>!'
Behind the scenes, untangle uses the built-in SAX parser, but because the library is implemented in pure Python and creates lots of heavyweight objects, it has considerably poor performance . While it's intended for reading tiny documents, you can still combine it with another approach to read multi-gigabyte XML files.
Here's how. If you head over to Wikipedia archives , you can download one of their compressed XML files. The one at the top should contain a snapshot of the articles' abstracts:
Language: XML<feed>
<doc>
<title>Wikipedia: Anarchism</title>
<url>https://en.wikipedia.org/wiki/Anarchism</url>
<abstract>Anarchism is a political philosophy...</abstract>
<links>
<sublink linktype="nav">
<anchor>Etymology, terminology and definition</anchor>
<link>https://en.wikipedia.org/wiki/Anarchism#Etymology...</link>
</sublink>
<sublink linktype="nav">
<anchor>History</anchor>
<link>https://en.wikipedia.org/wiki/Anarchism#History</link>
</sublink>
⋮
</links>
</doc>
⋮
</feed>
It's over 6 GB in size after download, which is perfect for this exercise. The idea is to scan the file to find the consecutive opening and closing <doc> tags and then parse the XML fragment between them using untangle for convenience.
The built-in mmap module lets you create a virtual view of the file contents, even when it doesn't fit the available memory. This gives an impression of working with a huge string of bytes that supports searching and the regular slicing syntax. If you're interested in how to encapsulate this logic in a Python class and take advantage of a generator for lazy evaluation, then expand the collapsible section below.
Here's the complete code of the XMLTagStream class:
import mmap
import untangle
class XMLTagStream:
def __init__(self, path, tag_name, encoding="utf-8"):
self.file = open(path)
self.stream = mmap.mmap(
self.file.fileno(), 0, access=mmap.ACCESS_READ
)
self.tag_name = tag_name
self.encoding = encoding
self.start_tag = f"<{tag_name}>".encode(encoding)
self.end_tag = f"</{tag_name}>".encode(encoding)
def __enter__(self):
return self
def __exit__(self, *args, **kwargs):
self.stream.close()
self.file.close()
def __iter__(self):
end = 0
while (begin := self.stream.find(self.start_tag, end)) != -1:
end = self.stream.find(self.end_tag, begin)
yield self.parse(self.stream[begin: end + len(self.end_tag)])
def parse(self, chunk):
document = untangle.parse(chunk.decode(self.encoding))
return getattr(document, self.tag_name)
It's a custom context manager , which uses the iterator protocol defined as an inline generator function . The resulting generator object loops over the XML document as if it was a long stream of characters.
Note that the while loop takes advantage of fairly new Python syntax, the walrus operator (:=) , to simplify the code. You can use this operator in assignment expressions , where an expression can be evaluated and assigned to a variable.
Without getting into the nitty-gritty details, here's how you can use this custom class to go through a big XML file quickly while inspecting specific elements more thoroughly with untangle:
>>> with XMLTagStream("abstract.xml", "doc") as stream:
... for doc in stream:
... print(doc.title.cdata.center(50, "="))
... for sublink in doc.links.sublink:
... print("-", sublink.anchor.cdata)
... if "q" == input("Press [q] to exit or any key to continue..."):
... break
...
===============Wikipedia: Anarchism===============
- Etymology, terminology and definition
- History
- Pre-modern era
⋮
Press [q] to exit or any key to continue...
================Wikipedia: Autism=================
- Characteristics
- Social development
- Communication
⋮
Press [q] to exit or any key to continue...
First, you open a file for reading and indicate the tag name that you want to find. Then, you iterate over those elements and receive a parsed fragment of the XML document. It's almost like looking through a tiny window moving over an infinitely long sheet of paper. That's a relatively surface-level example that ignores a few details, but it should give you a general idea of how to use such a hybrid parsing strategy.
Remove adsxmltodict: Convert XML to a Python DictionaryIf you like JSON but you're not a fan of XML, then check out xmltodict , which tries to bridge the gap between both data formats. As the name implies, the library can parse an XML document and represent it as a Python dictionary, which also happens to be the target data type for JSON documents in Python. This makes conversion between XML and JSON possible.
Note: Dictionaries are made up of key-value pairs, while XML documents are inherently hierarchical, which may lead to some information loss during the conversion. On top of that, XML has attributes, comments, processing instructions, and other ways of defining metadata that aren't available in dictionaries.
Unlike the rest of the XML parsers so far, this one expects either a Python string or a file-like object open for reading in binary mode:
Language: Python>>> import xmltodict
>>> xmltodict.parse("""\
... <svg viewBox="-105 -100 210 270">
... <!-- More content goes here... -->
... </svg>
... """)
OrderedDict([('svg', OrderedDict([('@viewBox', '-105 -100 210 270')]))])
>>> with open("smiley.svg", "rb") as file:
... xmltodict.parse(file)
...
OrderedDict([('svg', ...)])
By default, the library returns an instance of the OrderedDict collection to retain element order . However, starting from Python 3.6, plain dictionaries also keep the insertion order. If you'd like to work with regular dictionaries instead, then pass dict as the dict_constructor argument to the parse() function:
>>> import xmltodict
>>> with open("smiley.svg", "rb") as file:
... xmltodict.parse(file, dict_constructor=dict)
...
{'svg': ...}
Now, parse() returns a plain old dictionary with a familiar textual representation.
To avoid name conflicts between XML elements and their attributes, the library automatically prefixes the latter with an @ character. You may also ignore attributes completely by setting the xml_attribs flag appropriately:
>>> import xmltodict
>>> # Rename attributes by default
>>> with open("smiley.svg", "rb") as file:
... document = xmltodict.parse(file)
... print([x for x in document["svg"] if x.startswith("@")])
...
['@xmlns', '@xmlns:inkscape', '@viewBox', '@width', '@height']
>>> # Ignore attributes when requested
>>> with open("smiley.svg", "rb") as file:
... document = xmltodict.parse(file, xml_attribs=False)
... print([x for x in document["svg"] if x.startswith("@")])
...
[]
Yet another piece of information that gets ignored by default is the XML namespace declaration. These are treated like regular attributes, while the corresponding prefixes become part of the tag name. However, you can expand, rename, or skip some of the namespaces if you want to:
Language: Python>>> import xmltodict
>>> # Ignore namespaces by default
>>> with open("smiley.svg", "rb") as file:
... document = xmltodict.parse(file)
... print(document.keys())
...
odict_keys(['svg'])
>>> # Process namespaces when requested
>>> with open("smiley.svg", "rb") as file:
... document = xmltodict.parse(file, process_namespaces=True)
... print(document.keys())
...
odict_keys(['http://www.w3.org/2000/svg:svg'])
>>> # Rename and skip some namespaces
>>> namespaces = {
... "http://www.w3.org/2000/svg": "svg",
... "http://www.inkscape.org/namespaces/inkscape": None,
... }
>>> with open("smiley.svg", "rb") as file:
... document = xmltodict.parse(
... file, process_namespaces=True, namespaces=namespaces
... )
... print(document.keys())
... print("custom" in document["svg:svg"])
... print("inkscape:custom" in document["svg:svg"])
...
odict_keys(['svg:svg'])
True
False
In the first example above, tag names don't include the XML namespace prefix. In the second example, they do because you requested to process them. Finally, in the third example, you collapsed the default namespace to svg while suppressing Inkscape's namespace with None.
The default string representation of a Python dictionary might not be legible enough. To improve its presentation, you can pretty-print it or convert it to another format such as JSON or YAML :
Language: Python>>> import xmltodict
>>> with open("smiley.svg", "rb") as file:
... document = xmltodict.parse(file, dict_constructor=dict)
...
>>> from pprint import pprint as pp
>>> pp(document)
{'svg': {'@height': '270',
'@viewBox': '-105 -100 210 270',
'@width': '210',
'@xmlns': 'http://www.w3.org/2000/svg',
'@xmlns:inkscape': 'http://www.inkscape.org/namespaces/inkscape',
'defs': {'linearGradient': {'@id': 'skin',
⋮
>>> import json
>>> print(json.dumps(document, indent=4, sort_keys=True))
{
"svg": {
"@height": "270",
"@viewBox": "-105 -100 210 270",
"@width": "210",
"@xmlns": "http://www.w3.org/2000/svg",
"@xmlns:inkscape": "http://www.inkscape.org/namespaces/inkscape",
"defs": {
"linearGradient": {
⋮
>>> import yaml # Install first with 'pip install PyYAML'
>>> print(yaml.dump(document))
svg:
'@height': '270'
'@viewBox': -105 -100 210 270
'@width': '210'
'@xmlns': http://www.w3.org/2000/svg
'@xmlns:inkscape': http://www.inkscape.org/namespaces/inkscape
defs:
linearGradient:
⋮
The xmltodict library allows for converting the document the other way around -- that is, from a Python dictionary back to an XML string:
>>> import xmltodict
>>> with open("smiley.svg", "rb") as file:
... document = xmltodict.parse(file, dict_constructor=dict)
...
>>> xmltodict.unparse(document)
'<?xml version="1.0" encoding="utf-8"?>\n<svg...'
The dictionary may come in handy as an intermediate format when converting data from JSON or YAML to XML, should there be such a need.
There are a bunch more features in the xmltodict library, such as streaming, so feel free to explore them on your own. However, this library is a bit dated too. Besides, it's the next library that should be on your radar if you're really seeking advanced XML parsing features.
lxml: Use ElementTree on SteroidsIf you want the best performance, the broadest spectrum of functionality, and the most familiar interface all wrapped in one package, then install lxml and forget about the rest of the libraries. It's a Python binding for the C libraries libxml2 and libxslt , which support several standards, including XPath, XML Schema, and XSLT.
The library is compatible with Python's ElementTree API , which you learned about earlier in this tutorial. That means you can reuse your existing code by replacing only a single import statement:
Language: Pythonimport lxml.etree as ET
This will give you a great performance boost . On top of that, the lxml library comes with an extensive set of features and provides different ways of using them. For example, it lets you validate your XML documents against several schema languages, one of which is the XML Schema Definition:
>>> import lxml.etree as ET
>>> xml_schema = ET.XMLSchema(
... ET.fromstring("""\
... <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
... <xsd:element name="parent"/>
... <xsd:complexType name="SomeType">
... <xsd:sequence>
... <xsd:element name="child" type="xsd:string"/>
... </xsd:sequence>
... </xsd:complexType>
... </xsd:schema>"""))
>>> valid = ET.fromstring("<parent><child></child></parent>")
>>> invalid = ET.fromstring("<child><parent></parent></child>")
>>> xml_schema.validate(valid)
True
>>> xml_schema.validate(invalid)
False
None of the XML parsers in Python's standard library have the capability to validate documents. Meanwhile, lxml lets you define an XMLSchema object and run documents through it while remaining largely compatible with the ElementTree API.
Besides the ElementTree API, lxml supports an alternative lxml.objectify interface, which you'll cover later in the data binding section.
BeautifulSoup: Deal With Malformed XMLYou won't typically use the last library in this comparison for parsing XML since you mostly encounter it web scraping HTML documents. That said, it's capable of parsing XML just as well. BeautifulSoup comes with a pluggable architecture that lets you choose the underlying parser. The lxml one described earlier is actually recommended by the official documentation and is currently the only XML parser supported by the library.
Depending on the kind of documents you'll want to parse, the desired efficiency, and feature availability, you can select one of these parsers:
| Document Type | Parser Name | Python Library | Speed |
|---|---|---|---|
| HTML | "html.parser" |
- | Moderate |
| HTML | "html5lib" |
html5lib |
Slow |
| HTML | "lxml" |
lxml |
Fast |
| XML | "lxml-xml" or "xml" |
lxml |
Fast |
Other than speed, there are noticeable differences between the individual parsers. For example, some of them are more forgiving than others when it comes to malformed elements, while others emulate web browsers better.
Fun Fact: The library's name refers to the tag soup , which describes syntactically or structurally incorrect HTML code.
Assuming you've already installed the lxml and beautifulsoup4 libraries into your active virtual environment , you can start parsing XML documents right away. You only need to import BeautifulSoup:
from bs4 import BeautifulSoup
# Parse XML from a file object
with open("smiley.svg") as file:
soup = BeautifulSoup(file, features="lxml-xml")
# Parse XML from a Python string
soup = BeautifulSoup("""\
<svg viewBox="-105 -100 210 270">
<!-- More content goes here... -->
</svg>
""", features="lxml-xml")
If you accidentally specified a different parser, say lxml, then the library would add missing HTML tags such as <body> to the parsed document for you. That probably isn't what you intended in this case, so be careful when specifying the parser name.
BeautifulSoup is a powerful tool for parsing XML documents because it can handle invalid content and it has a rich API for extracting information. Have a look at how it copes with incorrectly nested tags, forbidden characters, and badly placed text:
Language: Python>>> from bs4 import BeautifulSoup
>>> soup = BeautifulSoup("""\
... <parent>
... <child>Forbidden < character </parent>
... </child>
... ignored
... """, features="lxml-xml")
>>> print(soup.prettify())
<?xml version="1.0" encoding="utf-8"?>
<parent>
<child>
Forbidden
</child>
</parent>
A different parser would raise an exception and surrender as soon as it detected something wrong with the document. Here, not only did it ignore the problems, but it also figured out sensible ways to fix some of them. The elements are properly nested now and have no invalid content.
There are way too many methods of locating elements with BeautifulSoup to cover them all here. Usually, you'll call a variant of .find() or .findall() on the soup element:
>>> from bs4 import BeautifulSoup
>>> with open("smiley.svg") as file:
... soup = BeautifulSoup(file, features="lxml-xml")
...
>>> soup.find_all("ellipse", limit=1)
[<ellipse cx="-20" cy="-10" fill="black" rx="6" ry="8" stroke="none"/>]
>>> soup.find(x=42)
<inkscape:custom inkscape:z="555" x="42">Some value</inkscape:custom>
>>> soup.find("stop", {"stop-color": "gold"})
<stop offset="75%" stop-color="gold" stop-opacity="1.0"/>
>>> soup.find(text=lambda x: "value" in x).parent
<inkscape:custom inkscape:z="555" x="42">Some value</inkscape:custom>
The limit parameter is similar to the LIMIT clause in MySQL, which lets you decide how many results you want to receive at most. It will return the specified number of results or fewer. That's no coincidence. You can think of these search methods as being a simple query language with powerful filters.
The search interface is very flexible but is outside the scope of this tutorial. You can check the library's documentation for more details or read yet another tutorial about web scraping in Python that touches on BeautifulSoup.
Say you want to consume a real-time data feed over a low-latency WebSocket connection with messages exchanged in XML format. For the purposes of this presentation, you're going to use a web browser to broadcast your mouse and keyboard events to the Python server. You'll build a custom protocol and use data binding to translate XML into native Python objects.
The idea behind data binding is to define a data model declaratively while letting the program figure out how to extract a valuable piece of information from the XML at runtime. If you've ever worked with Django models , then this concept should sound familiar.
First, begin by designing your data model. It's going to consist of two types of events:
KeyboardEventMouseEventEach can represent a few specialized subtypes, like a keypress or key release for the keyboard and a click or right-click for the mouse. Here's a sample XML message produced in response to holding down the Shift + 2 key combination:
Language: XML<KeyboardEvent>
<Type>keydown</Type>
<Timestamp>253459.17999999982</Timestamp>
<Key>
<Code>Digit2</Code>
<Unicode>@</Unicode>
</Key>
<Modifiers>
<Alt>false</Alt>
<Ctrl>false</Ctrl>
<Shift>true</Shift>
<Meta>false</Meta>
</Modifiers>
</KeyboardEvent>
This message contains a specific keyboard event type, a timestamp, the key code and its Unicode , as well as the modifier keys such as Alt , Ctrl , or Shift . The meta key is usually the Win or Cmd key, depending on your keyboard layout.
Similarly, a mouse event could look like this:
Language: XML<MouseEvent>
<Type>mousemove</Type>
<Timestamp>52489.07000000145</Timestamp>
<Cursor>
<Delta x="-4" y="8"/>
<Window x="171" y="480"/>
<Screen x="586" y="690"/>
</Cursor>
<Buttons bitField="0"/>
<Modifiers>
<Alt>false</Alt>
<Ctrl>true</Ctrl>
<Shift>false</Shift>
<Meta>false</Meta>
</Modifiers>
</MouseEvent>
Instead of the key, however, there's the mouse cursor position and a bit field encoding the mouse buttons pressed during the event. A bit field of zero indicates that no button was pressed.
As soon as a client makes the connection, it will start flooding the server with messages. The protocol won't consist of any handshakes, heartbeats, graceful shutdowns, topic subscriptions, or control messages. You can code this in JavaScript by registering event handlers and creating a WebSocket object in less than fifty lines of code.
However, implementing the client isn't the point of this exercise. Since you don't need to understand it, just expand the collapsible section below to reveal the HTML code with embedded JavaScript and save it in a file named whatever you like.
Language: HTML<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Real-Time Data Feed</title>
</head>
<body>
<script>
const ws = new WebSocket("ws://localhost:8000")
ws.onopen = event => {
["keydown", "keyup"].forEach(name =>
window.addEventListener(name, event =>
ws.send(`\
<KeyboardEvent>
<Type>${event.type}</Type>
<Timestamp>${event.timeStamp}</Timestamp>
<Key>
<Code>${event.code}</Code>
<Unicode>${event.key}</Unicode>
</Key>
<Modifiers>
<Alt>${event.altKey}</Alt>
<Ctrl>${event.ctrlKey}</Ctrl>
<Shift>${event.shiftKey}</Shift>
<Meta>${event.metaKey}</Meta>
</Modifiers>
</KeyboardEvent>`))
);
["mousedown", "mouseup", "mousemove"].forEach(name =>
window.addEventListener(name, event =>
ws.send(`\
<MouseEvent>
<Type>${event.type}</Type>
<Timestamp>${event.timeStamp}</Timestamp>
<Cursor>
<Delta x="${event.movementX}" y="${event.movementY}"/>
<Window x="${event.clientX}" y="${event.clientY}"/>
<Screen x="${event.screenX}" y="${event.screenY}"/>
</Cursor>
<Buttons bitField="${event.buttons}"/>
<Modifiers>
<Alt>${event.altKey}</Alt>
<Ctrl>${event.ctrlKey}</Ctrl>
<Shift>${event.shiftKey}</Shift>
<Meta>${event.metaKey}</Meta>
</Modifiers>
</MouseEvent>`))
)
}
</script>
</body>
</html>
The client connects to a local server listening on port 8000. Once you save the HTML code in a file, you'll be able to open it with your favorite web browser. But before that, you'll need to implement the server.
Python doesn't come with WebSocket support, but you can install the websockets library into your active virtual environment. You're also going to need lxml later, so it's a good moment to install both dependencies in one go:
$ python -m pip install websockets lxml
Finally, you can scaffold a minimal asynchronous web server:
Language: Python# server.py
import asyncio
import websockets
async def handle_connection(websocket, path):
async for message in websocket:
print(message)
if __name__ == "__main__":
future = websockets.serve(handle_connection, "localhost", 8000)
asyncio.get_event_loop().run_until_complete(future)
asyncio.get_event_loop().run_forever()
When you start the server and open the saved HTML file in a web browser, you should see XML messages appear in the standard output in response to your mouse moves and key presses. You can open the client in multiple tabs or even multiple browsers simultaneously!
Remove adsRight now, your messages arrive in plain string format. It's not very convenient to work with the messages in this format. Fortunately, you can turn them into compound Python objects with a single line of code using the lxml.objectify module:
# server.py
import asyncio
import websockets
import lxml.objectify
async def handle_connection(websocket, path):
async for message in websocket:
try:
xml = lxml.objectify.fromstring(message)
except SyntaxError:
print("Malformed XML message:", repr(message))
else:
if xml.tag == "KeyboardEvent":
if xml.Type == "keyup":
print("Key:", xml.Key.Unicode)
elif xml.tag == "MouseEvent":
screen = xml.Cursor.Screen
print("Mouse:", screen.get("x"), screen.get("y"))
else:
print("Unrecognized event type")
# ...
As long as the XML parsing is successful, you can inspect the root element's usual properties, such as the tag name, attributes, inner text, and so on. You'll be able to use the dot operator to navigate deep into the element tree. In most cases, the library will recognize a suitable Python data type and convert the value for you.
After saving those changes and restarting the server, you'll need to reload the page in your web browser to make a new WebSocket connection. Here's a sample output of the modified program:
Language: Shell$ python server.py
Mouse: 820 121
Mouse: 820 122
Mouse: 820 123
Mouse: 820 124
Mouse: 820 125
Key: a
Mouse: 820 125
Mouse: 820 125
Key: a
Key: A
Key: Shift
Mouse: 821 125
Mouse: 821 125
Mouse: 820 123
⋮
Sometimes, XML may contain tag names that aren't valid Python identifiers, or you might want to adapt the message structure to fit your data model. In such a case, an interesting option would be defining custom model classes with descriptors that declare how to look up information using XPath expressions. That's the part that starts to resemble Django models or Pydantic schema definitions.
You're going to use a custom XPath descriptor and an accompanying Model class, which provide reusable properties for your data models. The descriptor expects an XPath expression for element lookup in the received message. The underlying implementation is a bit advanced, so feel free to copy the code from the collapsible section below.
import lxml.objectify
class XPath:
def __init__(self, expression, /, default=None, multiple=False):
self.expression = expression
self.default = default
self.multiple = multiple
def __set_name__(self, owner, name):
self.attribute_name = name
self.annotation = owner.__annotations__.get(name)
def __get__(self, instance, owner):
value = self.extract(instance.xml)
instance.__dict__[self.attribute_name] = value
return value
def extract(self, xml):
elements = xml.xpath(self.expression)
if elements:
if self.multiple:
if self.annotation:
return [self.annotation(x) for x in elements]
else:
return elements
else:
first = elements[0]
if self.annotation:
return self.annotation(first)
else:
return first
else:
return self.default
class Model:
"""Abstract base class for your models."""
def __init__(self, data):
if isinstance(data, str):
self.xml = lxml.objectify.fromstring(data)
elif isinstance(data, lxml.objectify.ObjectifiedElement):
self.xml = data
else:
raise TypeError("Unsupported data type:", type(data))
Assuming you already have the desired XPath descriptor and the Model abstract base class in your module, you might use them to define KeyboardEvent and MouseEvent message types along with reusable building blocks to avoid repetition. There are infinite ways to do so, but here's one example:
# ...
class Event(Model):
"""Base class for event messages with common elements."""
type_: str = XPath("./Type")
timestamp: float = XPath("./Timestamp")
class Modifiers(Model):
alt: bool = XPath("./Alt")
ctrl: bool = XPath("./Ctrl")
shift: bool = XPath("./Shift")
meta: bool = XPath("./Meta")
class KeyboardEvent(Event):
key: str = XPath("./Key/Code")
modifiers: Modifiers = XPath("./Modifiers")
class MouseEvent(Event):
x: int = XPath("./Cursor/Screen/@x")
y: int = XPath("./Cursor/Screen/@y")
modifiers: Modifiers = XPath("./Modifiers")
The XPath descriptor allows for lazy evaluation so that elements of the XML messages are looked up only when requested. More specifically, they're only looked up when you access a property on the event object. Moreover, the results are cached to avoid running the same XPath query more than once. The descriptor also respects type annotations and converts deserialized data to the right Python type automatically.
Using those event objects isn't much different from the ones auto-generated by lxml.objectify before:
if xml.tag == "KeyboardEvent":
event = KeyboardEvent(xml)
if event.type_ == "keyup":
print("Key:", event.key)
elif xml.tag == "MouseEvent":
event = MouseEvent(xml)
print("Mouse:", event.x, event.y)
else:
print("Unrecognized event type")
There's an additional step of creating new objects of the specific event type. But other than that, it gives you more flexibility in terms of structuring your model independently of the XML protocol. Additionally, it's possible to derive new model attributes based on the ones in the received messages and add more methods on top of that.
Implementing model classes is a tedious and error-prone task. However, as long as your model mirrors the XML messages, you can take advantage of an automated tool to generate the necessary code for you based on XML Schema. The downside of such code is that it's usually less readable than if written by hand.
One of the oldest third-party modules to allow that was PyXB , which mimics Java's popular JAXB library. Unfortunately, it was last released several years ago and was targeting legacy Python versions. You can look into a similar yet actively maintained generateDS alternative, which generates data structures from XML Schema.
Let's say you have this models.xsd schema file describing your KeyboardEvent message:
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element name="KeyboardEvent" type="KeyboardEventType"/>
<xsd:complexType name="KeyboardEventType">
<xsd:sequence>
<xsd:element type="xsd:string" name="Type"/>
<xsd:element type="xsd:float" name="Timestamp"/>
<xsd:element type="KeyType" name="Key"/>
<xsd:element type="ModifiersType" name="Modifiers"/>
</xsd:sequence>
</xsd:complexType>
<xsd:complexType name="KeyType">
<xsd:sequence>
<xsd:element type="xsd:string" name="Code"/>
<xsd:element type="xsd:string" name="Unicode"/>
</xsd:sequence>
</xsd:complexType>
<xsd:complexType name="ModifiersType">
<xsd:sequence>
<xsd:element type="xsd:string" name="Alt"/>
<xsd:element type="xsd:string" name="Ctrl"/>
<xsd:element type="xsd:string" name="Shift"/>
<xsd:element type="xsd:string" name="Meta"/>
</xsd:sequence>
</xsd:complexType>
</xsd:schema>
A schema tells the XML parser what elements to expect, their order, and their level in the tree. It also restricts the allowed values for the XML attributes. Any discrepancies between these declarations and an actual XML document should render it invalid and make the parser reject the document.
Additionally, some tools can leverage this information to produce a piece of code that hides the details of XML parsing from you. After installing the library, you should be able to run the generateDS command in your active virtual environment:
$ generateDS -o models.py models.xsd
It will create a new file named models.py in the same directory with the generated Python source code. You can then import that module and use it to parse the incoming messages:
>>> from models import parseString
>>> event = parseString("""\
... <KeyboardEvent>
... <Type>keydown</Type>
... <Timestamp>253459.17999999982</Timestamp>
... <Key>
... <Code>Digit2</Code>
... <Unicode>@</Unicode>
... </Key>
... <Modifiers>
... <Alt>false</Alt>
... <Ctrl>false</Ctrl>
... <Shift>true</Shift>
... <Meta>false</Meta>
... </Modifiers>
... </KeyboardEvent>""", silence=True)
>>> event.Type, event.Key.Code
('keydown', 'Digit2')
It looks similar to the lxml.objectify example shown earlier. The difference is that using data binding enforces compliance with the schema, whereas lxml.objectify produces objects dynamically no matter if they're semantically correct.
The XML parsers in Python's standard library are vulnerable to a host of security threats that can lead to denial-of-service (DoS) or data loss, at best. That isn't their fault, to be fair. They just follow the specification of the XML standard, which is more complicated and powerful than most people know.
Note: Please be advised that you should use the information you're about to see wisely. You don't want to wind up being the attacker, exposing yourself to legal consequences, or facing lifetime banishment from using a particular service.
One of the most common attacks is the XML Bomb , also known as the billion laughs attack . The attack exploits entity expansion in DTD to blow up the memory and occupy the CPU for as long as possible. All you need to stop an unprotected web server from receiving new traffic are these few lines of XML code:
Language: Pythonimport xml.etree.ElementTree as ET
ET.fromstring("""\
<?xml version="1.0"?>
<!DOCTYPE lolz [
<!ENTITY lol "lol">
<!ELEMENT lolz (#PCDATA)>
<!ENTITY lol1 "&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;">
<!ENTITY lol2 "&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;">
<!ENTITY lol3 "&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;">
<!ENTITY lol4 "&lol3;&lol3;&lol3;&lol3;&lol3;&lol3;&lol3;&lol3;&lol3;&lol3;">
<!ENTITY lol5 "&lol4;&lol4;&lol4;&lol4;&lol4;&lol4;&lol4;&lol4;&lol4;&lol4;">
<!ENTITY lol6 "&lol5;&lol5;&lol5;&lol5;&lol5;&lol5;&lol5;&lol5;&lol5;&lol5;">
<!ENTITY lol7 "&lol6;&lol6;&lol6;&lol6;&lol6;&lol6;&lol6;&lol6;&lol6;&lol6;">
<!ENTITY lol8 "&lol7;&lol7;&lol7;&lol7;&lol7;&lol7;&lol7;&lol7;&lol7;&lol7;">
<!ENTITY lol9 "&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;">
]>
<lolz>&lol9;</lolz>""")
A naïve parser will try to resolve the custom entity &lol9; placed in the document root by inspecting the DTD. However, that entity itself refers to another entity several times, which refers to yet another entity, and so forth. When you run the script above, you'll notice something disturbing about your memory and the processing unit:
Look how the main memory and the swap partition are exhausted in just a matter of seconds while one of the CPUs works at 100% of its capacity. The recording stops abruptly when the system memory becomes full and then resumes after the Python process gets killed.
Another popular type of attack known as XXE takes advantage of general external entities to read local files and make network requests. Nevertheless, starting from Python 3.7.1, this feature has been disabled by default to increase security. If you trust your data, then you can tell the SAX parser to process external entities anyway:
Language: Python>>> from xml.sax import make_parser
>>> from xml.sax.handler import feature_external_ges
>>> parser = make_parser()
>>> parser.setFeature(feature_external_ges, True)
This parser will be able to read local files on your computer. It may pull usernames on a Unix-like operating system, for example:
Language: Python>>> from xml.dom.minidom import parseString
>>> xml = """\
... <?xml version="1.0" encoding="UTF-8"?>
... <!DOCTYPE root [
... <!ENTITY usernames SYSTEM "/etc/passwd">
... ]>
... <root>&usernames;</root>"""
>>> document = parseString(xml, parser)
>>> print(document.documentElement.toxml())
<root>root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
bin:x:2:2:bin:/bin:/usr/sbin/nologin
⋮
realpython:x:1001:1001:Real Python,,,:/home/realpython:/bin/bash
</root>
It's perfectly feasible to send that data over the network to a remote server!
Now, how can you protect yourself from such attacks? The Python official documentation prominently warns you about the risks of using the built-in XML parsers and recommends switching to an external package in mission-critical applications. While not distributed with Python, defusedxml is a drop-in replacement for all the parsers in the standard library.
The library imposes strict limits and disables a lot of the dangerous XML features. It should stop most of the well-known attacks, including the two just described. To use it, grab the library from PyPI and replace your import statements accordingly:
Language: Python>>> import defusedxml.ElementTree as ET
>>> ET.parse("bomb.xml")
Traceback (most recent call last):
...
raise EntitiesForbidden(name, value, base, sysid, pubid, notation_name)
defusedxml.common.EntitiesForbidden:
EntitiesForbidden(name='lol', system_id=None, public_id=None)
That's it! Forbidden features won't make it through anymore.
The XML data format is a mature and surprisingly powerful standard that is still in use today, especially in the enterprise setting. Choosing the right XML parser is crucial in finding the sweet spot between performance, security, compliance, and convenience.
This tutorial puts a detailed roadmap in your hand to navigate the confusing maze of XML parsers in Python. You know where to take the shortcuts and how to avoid dead ends, saving you lots of time.
In this tutorial, you learned how to:
Now, you understand the different strategies for parsing XML documents as well as their strengths and weaknesses. With this knowledge, you're able to pick the most suitable XML parser for your specific use case and even combine more than one to read multi-gigabyte XML files faster.
Liked it (thumbs up) Disliked it (thumbs down)🐍 Python Tricks 💌
Get a short & sweet Python Trick delivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team.
About Bartosz Zaczyński
Bartosz is an experienced software engineer and Python educator with an M.Sc. in Applied Computer Science.
» More about BartoszEach tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who worked on this tutorial are:
Aldren
David
Geir Arne
Sadie
Master Real-World Python Skills With Unlimited Access to Real Python
Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:
Master Real-World Python Skills
With Unlimited Access to Real Python
Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:
Keep Learning
Related Topics: intermediate stdlib tools
Related Learning Paths: