From 2fbf83106edefbba94741dff1104c0eac5f41aad Mon Sep 17 00:00:00 2001 From: Rohit Date: Wed, 1 Apr 2026 22:21:57 +0530 Subject: [PATCH] GH-113425: Add example for default_namespace in ElementTree docs --- Doc/library/xml.etree.elementtree.rst | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/Doc/library/xml.etree.elementtree.rst b/Doc/library/xml.etree.elementtree.rst index bbb15ce5e758c6..17f1a0d55f6d7d 100644 --- a/Doc/library/xml.etree.elementtree.rst +++ b/Doc/library/xml.etree.elementtree.rst @@ -365,8 +365,26 @@ These two approaches both output:: |--> Gunther |--> Commander Clement +Serializing XML with Default Namespace +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -.. _elementtree-xpath: +When serializing XML that contains a default namespace, ElementTree will by +default add a generated prefix (such as ``ns0``) instead of preserving the +default namespace. For example:: + + >>> root = ET.fromstring("

text

") + >>> print(ET.tostring(root, encoding='unicode')) + text + +To preserve the default namespace during serialization, use the +*default_namespace* parameter with :func:`tostring` or :meth:`ElementTree.write`:: + + >>> root = ET.fromstring("

text

") + >>> print(ET.tostring(root, encoding='unicode', default_namespace='http://example.com')) +

text

+ +.. versionadded:: 3.8 + The *default_namespace* parameter. XPath support -------------