diff --git a/Doc/library/xml.dom.minidom.rst b/Doc/library/xml.dom.minidom.rst
index 118e25430b93fc2..7e184071d27387f 100644
--- a/Doc/library/xml.dom.minidom.rst
+++ b/Doc/library/xml.dom.minidom.rst
@@ -151,6 +151,13 @@ module documentation. This section lists the differences between the API and
otherwise it is set to ``"no"``.
Not stating the argument will omit the declaration from the document.
+ :exc:`ValueError` is raised if the content of the node cannot be
+ represented in XML, for example if a comment contains ``"--"`` or
+ a CDATA section contains ``"]]>"``.
+ The characters are not checked:
+ the text, the attribute values and the content of comments,
+ processing instructions and CDATA sections are written as is.
+
.. versionchanged:: 3.8
The :meth:`writexml` method now preserves the attribute order specified
by the user.
diff --git a/Lib/test/test_minidom.py b/Lib/test/test_minidom.py
index 8c4de2e21553c17..0a67a49fde82b0b 100644
--- a/Lib/test/test_minidom.py
+++ b/Lib/test/test_minidom.py
@@ -2004,10 +2004,65 @@ def testDeepcopiedDocument(self):
doc2 = copy.deepcopy(doc)
self.assert_recursive_equal(doc, doc2)
- def testSerializeCommentNodeWithDoubleHyphen(self):
- doc = create_doc_without_doctype()
- doc.appendChild(doc.createComment("foo--bar"))
- self.assertRaises(ValueError, doc.toxml)
+ def testWriteXMLDoctypeIdentifiers(self):
+ impl = getDOMImplementation()
+ def serialize(publicId, systemId):
+ doctype = impl.createDocumentType("r", publicId, systemId)
+ return impl.createDocument(None, "r", doctype).toxml()[22:]
+ self.assertEqual(serialize(None, None), '')
+ self.assertEqual(serialize(None, "s"), "")
+ self.assertEqual(serialize("p", "s"),
+ "")
+ # the quote which is not in the literal is used
+ self.assertEqual(serialize("it's", "sys'tem"),
+ '')
+ # a system literal cannot contain both quotes
+ with self.assertRaisesRegex(ValueError, "both quotes"):
+ serialize(None, 'a"b\'c')
+ # a public identifier can only contain PubidChars
+ for publicId in ['pub"lic', 'p>', 'p<', 'p&', 'p[', '\xe9']:
+ with self.subTest(publicId=publicId):
+ with self.assertRaisesRegex(ValueError,
+ "invalid public identifier"):
+ serialize(publicId, "s")
+ # a public identifier is meaningless without a system identifier
+ with self.assertRaisesRegex(ValueError, "requires a system"):
+ serialize("p", None)
+
+ def testSerializeComment(self):
+ impl = getDOMImplementation()
+ def serialize(data):
+ doc = impl.createDocument(None, "r", None)
+ doc.documentElement.appendChild(doc.createComment(data))
+ return doc.toxml()[22:]
+ self.assertEqual(serialize("foo"), "")
+ self.assertEqual(serialize(""), "")
+ self.assertEqual(serialize("-foo"), "")
+ with self.assertRaisesRegex(ValueError, "'--' is not allowed"):
+ serialize("foo--bar")
+ # a trailing hyphen would be fused with the closing "-->"
+ with self.assertRaisesRegex(ValueError, "cannot end with"):
+ serialize("foo-")
+
+ def testSerializeProcessingInstruction(self):
+ impl = getDOMImplementation()
+ def serialize(target, data):
+ doc = impl.createDocument(None, "r", None)
+ pi = doc.createProcessingInstruction(target, data)
+ doc.documentElement.appendChild(pi)
+ return doc.toxml()[22:]
+ self.assertEqual(serialize("p", "a"), "")
+ self.assertEqual(serialize("p", ""), "")
+ self.assertEqual(serialize("xml-stylesheet", 'href="a"'),
+ '')
+ # "?>" would close the processing instruction
+ with self.assertRaisesRegex(ValueError, "'\\?>' is not allowed"):
+ serialize("p", "a?>b")
+ # the target "xml" is reserved
+ for target in ["xml", "XML", "XmL"]:
+ with self.subTest(target=target):
+ with self.assertRaisesRegex(ValueError, "reserved"):
+ serialize(target, "a")
def testEmptyXMLNSValue(self):
diff --git a/Lib/xml/dom/minidom.py b/Lib/xml/dom/minidom.py
index 6762853e91abdd7..402688df73be1b8 100644
--- a/Lib/xml/dom/minidom.py
+++ b/Lib/xml/dom/minidom.py
@@ -285,6 +285,27 @@ def __exit__(self, et, ev, tb):
defproperty(Node, "localName", doc="Namespace-local name of this node.")
+# PubidChar (see XML 1.0, 2.3, [13]).
+_PUBID_CHARS = frozenset(
+ " \r\n-'()+,./:=?;!*#@$_%"
+ "0123456789"
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
+ "abcdefghijklmnopqrstuvwxyz")
+
+
+def _quote_literal(text):
+ """Quote a system literal or a public identifier.
+
+ A literal is delimited with a quote which it does not contain
+ (see XML 1.0, 2.3, [11] and [12]).
+ """
+ if "'" not in text:
+ return "'%s'" % text
+ if '"' not in text:
+ return '"%s"' % text
+ raise ValueError("a literal cannot contain both quotes: %r" % (text,))
+
+
def _append_child(self, node):
# fast path with less checks; usable by DOM builders if careful
childNodes = self.childNodes
@@ -1026,7 +1047,18 @@ def _set_nodeName(self, value):
nodeName = property(_get_nodeName, _set_nodeName)
def writexml(self, writer, indent="", addindent="", newl=""):
- writer.write("%s%s %s?>%s" % (indent,self.target, self.data, newl))
+ target = self.target
+ # PITarget cannot match "xml" in any case (see XML 1.0, 2.6, [17]).
+ if target.lower() == "xml":
+ raise ValueError("%r is a reserved processing instruction target"
+ % (target,))
+ data = self.data
+ # The data cannot contain "?>", which ends the instruction
+ # (see XML 1.0, 2.6, [16]).
+ if "?>" in data:
+ raise ValueError("'?>' is not allowed in a processing "
+ "instruction node")
+ writer.write("%s%s %s?>%s" % (indent, target, data, newl))
class CharacterData(Childless, Node):
@@ -1221,9 +1253,14 @@ def __init__(self, data):
self._data = data
def writexml(self, writer, indent="", addindent="", newl=""):
- if "--" in self.data:
+ data = self.data
+ # The data cannot contain "--", and cannot end with "-", which
+ # would be fused with the closing "-->" (see XML 1.0, 2.5, [15]).
+ if "--" in data:
raise ValueError("'--' is not allowed in a comment node")
- writer.write("%s%s" % (indent, self.data, newl))
+ if data.endswith("-"):
+ raise ValueError("a comment node cannot end with '-'")
+ writer.write("%s%s" % (indent, data, newl))
class CDATASection(Text):
@@ -1369,10 +1406,20 @@ def writexml(self, writer, indent="", addindent="", newl=""):
writer.write("`` in the data
+or using the reserved target ``xml``.
+The characters are still not checked.