Python Glossary Русский

all Python 3xml.etree.ElementTreefunction

xml.etree.ElementTree.Comment()

comments and instructions

A comment factory: returns a special element serialized as <!-- … -->. The function itself serves as its tag.

Syntax

c = ET.Comment(text=None)

A comment element's tag is the ET.Comment function itself, not a string, so code like elem.tag.startswith(...) crashes with AttributeError when the tree contains comments; test elem.tag is ET.Comment. fromstring() drops comments, so they appear in the tree only if inserted by hand or via TreeBuilder(insert_comments=True). A '--' inside the text is not escaped and yields invalid XML.

Examples

import xml.etree.ElementTree as ET
root = ET.Element('cfg')
root.append(ET.Comment(' generated '))
ET.SubElement(root, 'port').text = '80'
print(ET.tostring(root, encoding='unicode'))
# → <cfg><!-- generated --><port>80</port></cfg>
print([e.tag for e in root if isinstance(e.tag, str)])  # → ['port']
print(root[0].tag is ET.Comment)  # → True

See also

Open in the full glossarydocs.python.orgReport an inaccuracy