fromstring, findall, and ParseError
xml.etree.ElementTree.fromstring(text, parser=None)
Element.find(path, namespaces=None)
Element.findall(path, namespaces=None)
xml.etree.ElementTree.ParseErrorfromstring parses an XML string into an Element. Malformed markup raises ParseError. No file or URL is opened here.
| Parameter | Description |
|---|---|
text | XML as a string (or bytes). This example uses a str and does not fetch a document. |
parser | Optional custom XMLParser. The default parser is used when omitted. |
path | A find path such as a child tag name, or a limited XPath subset documented in the official reference. |
Returns: fromstring returns the root Element. find returns an Element or None. findall returns a list of elements.
Raises
ParseError— Raised when the text is not well-formed XML. The exception carries an error message and a position.
- This fragment does not parse untrusted input and does not demonstrate entity expansion.
import xml.etree.ElementTree as ET
root = ET.fromstring('<box><item id="a">one</item><item id="b">two</item></box>')
print(root.tag)
print([child.get('id') for child in root.findall('item')])
print(root.find('item').text)
try:
ET.fromstring('<box><item></box>')
except ET.ParseError as exc:
print(type(exc).__name__)
print(exc)Expected output
box
['a', 'b']
one
ParseError
mismatched tag: line 1, column 13
Related: XML diff tool, XML formatter, Official XML security