Skip to content

Commit e9cceb2

Browse files
committed
gh-158208: Don't write a duplicate xmlns attribute in xml.dom.minidom
Since gh-44376, _fixup_namespaces() adds xmlns="" to an element in no namespace under a default namespace. When the element declares the default namespace itself, as one built with createElement() and setAttribute("xmlns", ...) does, its own xmlns attribute was written too, so the output was not well-formed. Do not add the undeclaration if the element already has an xmlns attribute. The default namespace is still treated as undeclared for its children, so they are written as before.
1 parent ee1bbf0 commit e9cceb2

2 files changed

Lines changed: 24 additions & 1 deletion

File tree

‎Lib/test/test_minidom.py‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -702,6 +702,28 @@ def testWriteXMLNotANamespaceDeclaration(self):
702702
'<child xmlns="" xmlnsabc="v"/></root>')
703703
dom.unlink()
704704

705+
def testWriteXMLOwnDefaultNamespaceDeclaration(self):
706+
# An element in no namespace which declares the default namespace
707+
# itself is written with that declaration only.
708+
dom = Document()
709+
svg = dom.appendChild(dom.createElement("svg"))
710+
svg.setAttribute("xmlns", "http://www.w3.org/2000/svg")
711+
svg.appendChild(dom.createElement("g"))
712+
self.assertEqual(dom.documentElement.toxml(),
713+
'<svg xmlns="http://www.w3.org/2000/svg"><g/></svg>')
714+
dom.unlink()
715+
716+
dom = Document()
717+
root = dom.appendChild(
718+
dom.createElementNS("http://xml.python.org/ns", "root"))
719+
svg = root.appendChild(dom.createElement("svg"))
720+
svg.setAttribute("xmlns", "http://www.w3.org/2000/svg")
721+
svg.appendChild(dom.createElement("g"))
722+
self.assertEqual(dom.documentElement.toxml(),
723+
'<root xmlns="http://xml.python.org/ns">'
724+
'<svg xmlns="http://www.w3.org/2000/svg"><g/></svg></root>')
725+
dom.unlink()
726+
705727
def testWriteXMLDoesNotModifyDocument(self):
706728
dom = Document()
707729
root = dom.appendChild(

‎Lib/xml/dom/minidom.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -449,7 +449,8 @@ def _fixup_namespaces(element, nsmap):
449449
elif nsmap.get(None) and ':' not in element.tagName:
450450
# The element is in no namespace, undeclare the default one.
451451
nsmap = _bind_namespace(nsmap, inherited, None, None)
452-
declarations.append(("xmlns", ""))
452+
if not element.hasAttribute("xmlns"):
453+
declarations.append(("xmlns", ""))
453454

454455
items = []
455456
prefixes = None # namespace URI -> prefix, built only when needed

0 commit comments

Comments
 (0)