Skip to content

Commit 2fbf831

Browse files
author
Rohit
committed
GH-113425: Add example for default_namespace in ElementTree docs
1 parent 9e5b838 commit 2fbf831

File tree

1 file changed

+19
-1
lines changed

1 file changed

+19
-1
lines changed

Doc/library/xml.etree.elementtree.rst

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -365,8 +365,26 @@ These two approaches both output::
365365
|--> Gunther
366366
|--> Commander Clement
367367

368+
Serializing XML with Default Namespace
369+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
368370

369-
.. _elementtree-xpath:
371+
When serializing XML that contains a default namespace, ElementTree will by
372+
default add a generated prefix (such as ``ns0``) instead of preserving the
373+
default namespace. For example::
374+
375+
>>> root = ET.fromstring("<doc xmlns='http://example.com'><p>text</p></doc>")
376+
>>> print(ET.tostring(root, encoding='unicode'))
377+
<ns0:doc xmlns:ns0="http://example.com"><ns0:p>text</ns0:p></ns0:doc>
378+
379+
To preserve the default namespace during serialization, use the
380+
*default_namespace* parameter with :func:`tostring` or :meth:`ElementTree.write`::
381+
382+
>>> root = ET.fromstring("<doc xmlns='http://example.com'><p>text</p></doc>")
383+
>>> print(ET.tostring(root, encoding='unicode', default_namespace='http://example.com'))
384+
<doc xmlns="http://example.com"><p>text</p></doc>
385+
386+
.. versionadded:: 3.8
387+
The *default_namespace* parameter.
370388

371389
XPath support
372390
-------------

0 commit comments

Comments
 (0)