diff --git a/Lib/test/test_minidom.py b/Lib/test/test_minidom.py
index 446bbe096bd19dc..d0310bf41b6a3b2 100644
--- a/Lib/test/test_minidom.py
+++ b/Lib/test/test_minidom.py
@@ -612,6 +612,21 @@ def testWriteXMLDefaultNamespace(self):
'')
dom.unlink()
+ def testWriteXMLNoDuplicateXmlns(self):
+ # gh-158208: setting an explicit xmlns attribute must not
+ # result in a duplicate xmlns declaration in the output.
+ dom = Document()
+ svg = dom.appendChild(dom.createElement("svg"))
+ svg.setAttribute("xmlns", "https://www.w3.org/2000/svg")
+ xml = dom.toxml()
+ self.assertEqual(
+ xml,
+ ''
+ )
+ # The result must be well-formed XML.
+ parseString(xml)
+ dom.unlink()
+
def testWriteXMLAttributeNamespacePrefix(self):
dom = Document()
root = dom.appendChild(dom.createElement("root"))
diff --git a/Lib/xml/dom/minidom.py b/Lib/xml/dom/minidom.py
index 7cb652a323dcc22..afddc72eb24ab97 100644
--- a/Lib/xml/dom/minidom.py
+++ b/Lib/xml/dom/minidom.py
@@ -424,6 +424,7 @@ def _fixup_namespaces(element, nsmap):
declarations = []
# (name, value, namespace URI, attribute) of the attributes to write.
entries = []
+ has_own_xmlns = False
if attrs:
for attr in attrs.values():
name = attr.name
@@ -435,6 +436,8 @@ def _fixup_namespaces(element, nsmap):
nsmap, inherited,
attr.localName if attr.prefix else None, attr.value)
attr_uri = None
+ if name == "xmlns":
+ has_own_xmlns = True
elif attr_uri == XML_NAMESPACE:
# The xml prefix is bound by definition.
attr_uri = None
@@ -446,8 +449,10 @@ def _fixup_namespaces(element, nsmap):
if nsmap.get(prefix) != uri:
nsmap = _bind_namespace(nsmap, inherited, prefix, uri)
declarations.append(("xmlns:" + prefix if prefix else "xmlns", uri))
- elif nsmap.get(None) and ':' not in element.tagName:
+ elif (nsmap.get(None) and ':' not in element.tagName
+ and not has_own_xmlns):
# The element is in no namespace, undeclare the default one.
+ # Don't undeclare if the element itself declared xmlns.
nsmap = _bind_namespace(nsmap, inherited, None, None)
declarations.append(("xmlns", ""))
diff --git a/Misc/NEWS.d/next/Library/2026-09-26-11-53-32.gh-issue-158208.AbCdEf.rst b/Misc/NEWS.d/next/Library/2026-09-26-11-53-32.gh-issue-158208.AbCdEf.rst
new file mode 100644
index 000000000000000..d9413356c37fcd4
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-09-26-11-53-32.gh-issue-158208.AbCdEf.rst
@@ -0,0 +1,3 @@
+Fix :mod:`xml.dom.minidom` to not write a duplicate ``xmlns`` attribute
+when an element has an explicit ``xmlns`` attribute set with
+:meth:`~xml.dom.Element.setAttribute`.