From d1fbe6c6fcb75a34ae9cf15fc1f67b71fea7e652 Mon Sep 17 00:00:00 2001 From: Asif Saif Uddin Date: Wed, 30 Apr 2025 14:14:26 +0600 Subject: [PATCH 1/2] gh-49099: Add new optional arguments to minidom.Element constructor. --- Lib/xml/dom/minidom.py | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/Lib/xml/dom/minidom.py b/Lib/xml/dom/minidom.py index db51f350ea0153..f1991b507513e7 100644 --- a/Lib/xml/dom/minidom.py +++ b/Lib/xml/dom/minidom.py @@ -695,12 +695,16 @@ class Element(Node): Node.ENTITY_REFERENCE_NODE) def __init__(self, tagName, namespaceURI=EMPTY_NAMESPACE, prefix=None, - localName=None): + localName=None, childNodes=None, attributes=None, attributesNS=None): self.parentNode = None + self.ownerDocument = None self.tagName = self.nodeName = tagName self.prefix = prefix self.namespaceURI = namespaceURI self.childNodes = NodeList() + if childNodes: + for child in childNodes: + self.appendChild(child) self.nextSibling = self.previousSibling = None # Attribute dictionaries are lazily created @@ -713,6 +717,13 @@ def __init__(self, tagName, namespaceURI=EMPTY_NAMESPACE, prefix=None, # namespaces. self._attrs = None self._attrsNS = None + if attributes: + for name, value in attributes.items(): + self.setAttribute(name, value) + + if attributesNS: + for (namespace, name), value in attributesNS.items(): + self.setAttributeNS(namespace, name, value) def _ensure_attributes(self): if self._attrs is None: From 7535f0e924634f89abf319db0ac254c93636c9a0 Mon Sep 17 00:00:00 2001 From: Asif Saif Uddin Date: Wed, 30 Apr 2025 14:44:53 +0600 Subject: [PATCH 2/2] added initial unittest --- Lib/test/test_minidom.py | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/Lib/test/test_minidom.py b/Lib/test/test_minidom.py index 4f25e9c2a03cb4..853368306043d4 100644 --- a/Lib/test/test_minidom.py +++ b/Lib/test/test_minidom.py @@ -1741,5 +1741,38 @@ def test_cdata_parsing(self): dom2 = parseString(dom1.toprettyxml()) self.checkWholeText(dom2.getElementsByTagName('node')[0].firstChild, '') + def testElementConstructor(self): + dom = parse(tstfile) + child1 = dom.createComment("Hello 1") + child2 = dom.createComment("Hello 2") + + attributes = { + "first": "1", + "second": "2", + } + + attributesNS = { + ("http://www.w3.org", "xmlns:python"): "http://www.python.org", + } + + element = xml.dom.minidom.Element( + "some_tag", + childNodes=[child1, child2], + attributes=attributes, + attributesNS=attributesNS + ) + + self.assertEqual(child1.data, element.childNodes[0].data) + self.assertEqual(child2.data, element.childNodes[1].data) + + for name, value in attributes.items(): + self.assertEqual(value, element.getAttribute(name)) + + self.assertEqual( + element.getAttributeNS( + "http://www.w3.org", "python"), + "http://www.python.org" + ) + if __name__ == "__main__": unittest.main()