Python Glossary Русский

all Python 3xml.etree.ElementTreefunction

xml.etree.ElementTree.fromstring()

parsing

Parses XML from a string (str or bytes) and returns the root Element, not an ElementTree. ET.XML is the same function.

Syntax

root = ET.fromstring(text, parser=None)

An element's text comes in two parts: text is what precedes the first child tag, and tail follows the closing tag and belongs to the child. So in <p>Hello <b>world</b>!</p> the exclamation mark lives in b.tail, not p.text, and a naive walk over .text loses pieces. An empty element has text None, not ''. The standard parser offers no protection against entity-expansion bombs such as billion laughs, so use the third-party defusedxml for untrusted input. ET.XML and ET.fromstring are the very same object.

Examples

import xml.etree.ElementTree as ET
p = ET.fromstring('<p>Hello <b>world</b>!</p>')
print(repr(p.text), repr(p[0].text), repr(p[0].tail))  # → 'Hello ' 'world' '!'
print(''.join(p.itertext()))  # → Hello world!
print(ET.fromstring('<a/>').text)  # → None
print(ET.XML is ET.fromstring)  # → True

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy