Skip to content

gh-49099: Add new optional arguments to minidom.Element constructor. #133191

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions Lib/test/test_minidom.py
Original file line number Diff line number Diff line change
Expand Up @@ -1741,5 +1741,38 @@ def test_cdata_parsing(self):
dom2 = parseString(dom1.toprettyxml())
self.checkWholeText(dom2.getElementsByTagName('node')[0].firstChild, '</data>')

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()
13 changes: 12 additions & 1 deletion Lib/xml/dom/minidom.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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:
Expand Down
Loading