Featureadvanced
XML and HTML modules
Also called xml.etree.ElementTree, ElementTree, xml.dom.minidom, minidom, html.parser, HTMLParser, html.escape, XML parsing, XML security.
xml.etree.ElementTree parses and builds XML as a tree of elements, and xml.dom.minidom offers a small DOM. The html package escapes text and has a simple HTML parser. Untrusted XML needs care.
- Language
- Python
Synopsis
import xml.etree.ElementTree as ET
doc = """<library>
<book id="b1" year="1978"><title>The C Programming Language</title></book>
<book id="b2" year="1985"><title>Structure and Interpretation of Computer Programs</title></book>
</library>"""
root = ET.fromstring(doc)
for book in root.findall("book"):
print(book.get("id"), book.get("year"), book.find("title").text)
print(root.find("book[@year='1985']/title").text)
b1 1978 The C Programming Language
b2 1985 Structure and Interpretation of Computer Programs
Structure and Interpretation of Computer Programs
Semantics
r1. "Python supports a variety of modules to work with various forms of structured data markup."1 For XML, the main one is ElementTree, which "implements a simple and efficient API for parsing and creating XML data."2 Example: parse.
r2. fromstring returns the root Element. "Element.findall() finds only elements with a tag which are direct children of the current element. Element.find() finds the first child with a particular tag, and Element.text accesses the element’s text content. Element.get() accesses the element’s attributes."2 Example: parse.
r3. The find methods take a path. The module "provides limited support for XPath expressions for locating elements in a tree."2 A path such as book[@year='1985']/title filters by an attribute.
r4. An element has text and tail. The text is "the text between the element’s start tag and its first child or end tag", and the tail is "the text between the element’s end tag and the next tag".2 Example: mixed-content.
r5. In a document with namespaces, tags "get expanded to {uri}sometag where the prefix is replaced by the full URI. Also, if there is a default namespace, that full URI gets prepended to all of the non-prefixed tags."2 Example: namespaces.
r6. xml.dom.minidom "is a minimal implementation of the Document Object Model interface, with an API similar to that in other languages."3 Example: minidom.
r7. html.escape converts "the characters &, < and > in string s to HTML-safe sequences."4 By default it converts the quote characters too. html.unescape does the reverse. Example: html-tools.
r8. html.parser.HTMLParser is a base class: you subclass it and override the handler methods, such as handle_starttag and handle_data. For a start tag, "The tag argument is the name of the tag converted to lower case."5 Example: html-tools.
r9. "An attacker can abuse XML features to carry out denial of service attacks, access local files, generate network connections to other machines, or circumvent firewalls when attacker-controlled XML is being parsed, in Python or elsewhere."6 The XML security section lists the attacks for each parser.
Examples
import xml.etree.ElementTree as ET
root = ET.Element("config", version="2")
server = ET.SubElement(root, "server")
server.text = "a < b & c"
ET.SubElement(root, "debug", enabled="false")
print(ET.tostring(root, encoding="unicode"))
ET.indent(root)
print(ET.tostring(root, encoding="unicode"))
<config version="2"><server>a < b & c</server><debug enabled="false" /></config>
<config version="2">
<server>a < b & c</server>
<debug enabled="false" />
</config>
SubElement makes a child and adds it to the parent. tostring escapes < and & in the text. indent "Appends whitespace to the subtree to indent the tree visually."2
import xml.etree.ElementTree as ET
doc = """<feed xmlns="http://www.w3.org/2005/Atom">
<entry><title>First</title></entry>
<entry><title>Second</title></entry>
</feed>"""
root = ET.fromstring(doc)
print(root.tag)
print(root.findall("entry"))
ns = {"atom": "http://www.w3.org/2005/Atom"}
print([e.find("atom:title", ns).text for e in root.findall("atom:entry", ns)])
{http://www.w3.org/2005/Atom}feed
[]
['First', 'Second']
The default namespace is part of every tag name, so findall("entry") finds nothing (rule r5). Pass a dict of prefixes, and use the prefix in the path.
from xml.dom import minidom
dom = minidom.parseString("<menu><item price='3'>tea</item><item price='5'>cake</item></menu>")
for item in dom.getElementsByTagName("item"):
print(item.getAttribute("price"), item.firstChild.data)
print(dom.documentElement.toprettyxml(indent=" "), end="")
3 tea
5 cake
<menu>
<item price="3">tea</item>
<item price="5">cake</item>
</menu>
The DOM methods have the names of the W3C DOM, such as getElementsByTagName (rule r6). In the DOM, the text is a child node, so firstChild.data reads it.
import html
from html.parser import HTMLParser
text = '<script>alert("x")</script> & more'
safe = html.escape(text)
print(safe)
print(html.unescape(safe) == text, html.unescape("éé>"))
class LinkParser(HTMLParser):
def __init__(self):
super().__init__()
self.links = []
def handle_starttag(self, tag, attrs):
if tag == "a":
self.links.append(dict(attrs).get("href"))
parser = LinkParser()
parser.feed('<p>See <a href="/docs">docs</a> and <A HREF="https://example.com">this<p>')
print(parser.links)
<script>alert("x")</script> & more
True éé>
['/docs', 'https://example.com']
escape makes text safe to put in an HTML page (rule r7). The parser gives tag and attribute names in lower case, so <A HREF=...> matches 'a' (rule r8). It accepts HTML that is not well formed: "This parser does not check that end tags match start tags".5
Versions
Since 3.9
is new.2
Pitfalls
This code runs but gives a wrong answer on purpose.
import xml.etree.ElementTree as ET
p = ET.fromstring("<p>Hello <b>big</b> world</p>")
print(repr(p.text), repr(p.find("b").text), repr(p.find("b").tail))
print("".join(p.itertext()))
'Hello ' 'big' ' world'
Hello big world
p.text is only 'Hello '. The text after <b> is the tail of b, not part of p.text (rule r4). Use itertext to get all the text of an element.
This code raises ParseError, on purpose.
import xml.etree.ElementTree as ET
ET.fromstring("<a><b>text</a></b>")
XML must be well formed, so the parser stops at the first wrong end tag. The HTML parser is different and accepts such input (rule r8).
Do not test an element with if element:. "Caution: Elements with no subelements will test as False."2 Use element is not None to check the result of find, and len(element) to count the children.
Comparison
ElementTree is the usual choice in Python. The minidom docs say "Users who are not already proficient with the DOM should consider using the xml.etree.ElementTree module for their XML processing instead."3 Code that already uses the W3C DOM API in another language maps more directly to minidom. For data files that are not markup, see File format modules. Before you parse XML from an untrusted source, read the XML security section of the docs (rule r9).
References
- Structured Markup Processing Tools, Python 3.15 documentation, Structured Markup Processing Tools
- xml.etree.ElementTree, The ElementTree XML API, Python 3.15 documentation, Tutorial; Parsing XML with Namespaces; XPath support; indent(); Element objects
- xml.dom.minidom, Minimal DOM implementation, Python 3.15 documentation, Introduction
- html, HyperText Markup Language support, Python 3.15 documentation, escape(); unescape()
- html.parser, Simple HTML and XHTML parser, Python 3.15 documentation, Introduction; HTMLParser methods
- XML Processing Modules, Python 3.15 documentation, Introduction; XML security
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag 9H96PB Edit this page History Report an error Markdown