gh-54092: Implement writexml() for DocumentFragment in xml.dom.minido… · python/cpython@9bd9c74 · GitHub
Skip to content

Commit 9bd9c74

Browse files
gh-54092: Implement writexml() for DocumentFragment in xml.dom.minidom (GH-156646)
toxml() and toprettyxml() now work for document fragments. They write the children of the fragment, without adding a level of indentation.
1 parent a4ca6e8 commit 9bd9c74

5 files changed

Lines changed: 36 additions & 0 deletions

File tree

Doc/library/xml.dom.minidom.rst

Lines changed: 5 additions & 0 deletions

Doc/whatsnew/3.16.rst

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -725,6 +725,12 @@ xml
725725
rather than defaulted from the DTD.
726726
(Contributed by Jason Orendorff and Serhiy Storchaka in :gh:`44871`.)
727727

728+
* The :meth:`~xml.dom.minidom.Node.writexml`,
729+
:meth:`~xml.dom.minidom.Node.toxml` and
730+
:meth:`~xml.dom.minidom.Node.toprettyxml` methods
731+
now work for :class:`!DocumentFragment` nodes in :mod:`xml.dom.minidom`.
732+
(Contributed by Serhiy Storchaka in :gh:`54092`.)
733+
728734
* :class:`~xml.etree.ElementTree.XMLPullParser` and
729735
:func:`~xml.etree.ElementTree.iterparse` now support the *target* parameter.
730736
The reported object is the value returned by the corresponding method of

Lib/test/test_minidom.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -571,6 +571,21 @@ def testWriteXML(self):
571571
dom.unlink()
572572
self.assertEqual(str, domstr)
573573

574+
def testWriteXMLDocumentFragment(self):
575+
dom = parseString('<doc><a b="c"/>text<!--comment--></doc>')
576+
frag = dom.createDocumentFragment()
577+
for node in list(dom.documentElement.childNodes):
578+
frag.appendChild(node)
579+
self.assertEqual(frag.toxml(), '<a b="c"/>text<!--comment-->')
580+
self.assertEqual(frag.toprettyxml(),
581+
'<a b="c"/>\ntext\n<!--comment-->\n')
582+
# the fragment itself does not add a level of indentation
583+
writer = io.StringIO()
584+
frag.writexml(writer, " ", " ", "\n")
585+
self.assertEqual(writer.getvalue(),
586+
' <a b="c"/>\n text\n <!--comment-->\n')
587+
self.assertEqual(dom.createDocumentFragment().toxml(), '')
588+
574589
def testWriteXMLNamespaceDeclarations(self):
575590
dom = Document()
576591
root = dom.appendChild(

Lib/xml/dom/minidom.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -515,6 +515,10 @@ class DocumentFragment(Node):
515515
def __init__(self):
516516
self.childNodes = NodeList()
517517

518+
def writexml(self, writer, indent="", addindent="", newl=""):
519+
for node in self.childNodes:
520+
node.writexml(writer, indent, addindent, newl)
521+
518522

519523
class Attr(Node):
520524
__slots__=('_name', '_value', 'namespaceURI',
Lines changed: 6 additions & 0 deletions

0 commit comments

Comments
 (0)