Taskcore
Read and write XML
Also called parse and serialize XML, XML round trip, canonicalize XML.
Parse an XML text with the parser of the standard library, then write the root element back in a fixed form that follows Canonical XML, so that texts with the same data give the same output.
- Evidence
- Code in 4 languages
Task
Parse an XML text into a tree, then write the tree back as text. Each solution is a function xml_rewrite(text) that parses the text with the XML parser of its standard library and writes the root element back in one fixed form. The parser does the reading, and the solution does the writing with its own code, so that the output does not depend on the defaults of a library serializer.
Two texts that differ only in ways that XML permits give the same output. Such differences are the quote characters around an attribute value, the order of the attributes, <item/> against <item></item>, a CDATA section against escaped text, and a character reference against the character itself. A test can compare two documents in this way, and a program can check that its writer keeps the data of the tree.
The fixed form follows the rules of Canonical XML. RFC 3076 gives the purpose: "if two documents have the same canonical form, then the two documents are logically equivalent within the given application context."1 The rules that the contract uses are these:
- An element is written as a start tag, its content and an end tag. "Empty elements are converted to start-end tag pairs"1, so
<item/>becomes<item></item>. - Each attribute is written as a space, the qualified name,
=and the value in double quotes. The namespace declarations come first, and "the default namespace node, if one exists, has no local name and is therefore lexicographically least"1. The other declarations follow in the order of their prefixes, and then the other attributes in the order of their qualified names. The order compares code points. - In an attribute value, the solution replaces "all ampersands (&) with &, all open angle brackets (<) with <, all quotation mark (double quote) characters with ", and the whitespace characters #x9, #xA, and #xD, with character references"1. The references are
	,
and
. - In text, "all ampersands are replaced by &, all open angle brackets (<) are replaced by <, all closing angle brackets (>) are replaced by >, and all #xD characters are replaced by ."1 Each other character is written as itself, also when it is not ASCII.
- The parser replaces the references and removes the CDATA markers: "Character and parsed entity references are replaced" and "CDATA sections are replaced with their character content"1. The parser also changes each line end to a line feed: "Line breaks normalized to #xA on input, before parsing"1.
- The XML declaration, comments, processing instructions and all content outside the root element are not written.
The contract is not full Canonical XML. Canonical XML sorts the attributes "with namespace URI as the primary key and local name as the secondary key"1, and the contract sorts them by qualified name. The two orders are the same when no attribute has a prefix. Canonical XML also keeps the processing instructions, can keep the comments, and removes the namespace declarations that an ancestor already makes.
The solution reports parse-error when the text is not well-formed XML or when it has a document type declaration (<!DOCTYPE).
Solutions
Python, Java, C# and Go have an XML parser in the standard library. The standard libraries of JavaScript (Node.js), TypeScript, Rust, C, C++ and Bash do not, and matrix.yaml names the usual libraries.
- Python.
xml.dom.minidom.parseStringreturns "a Document that represents the string"2, and the solution walks the DOM tree. It does not use ElementTree, because ElementTree does not keep the prefixes of the text (see Pitfalls). Python also hasElementTree.canonicalize, a "C14N 2.0 transformation function"3. Its output is close to the contract, but it keeps processing instructions and drops the declarations of prefixes that no name uses:
import xml.etree.ElementTree as ET
for text in ['<a v="	">x<!-- note -->y<?app data?>z</a>', '<r xmlns="urn:d" xmlns:m="urn:m" b="2" a="1"/>']:
print(ET.canonicalize(text))
<a v="	">xy<?app data?>z</a>
<r xmlns="urn:d" a="1" b="2"></r>
The contract gives <a v="	">xyz</a> and <r xmlns="urn:d" xmlns:m="urn:m" a="1" b="2"></r> for these two texts.
- Java. The solution makes the parser with
DocumentBuilderFactory.newDefaultInstance(), which "Creates a new instance of the DocumentBuilderFactory builtin system-default implementation."4 It setssetNamespaceAware(true), the featuredisallow-doctype-declandFEATURE_SECURE_PROCESSING, as the OWASP cheat sheet shows for the DOM parser5. The DOM gives the namespace declarations as attributes, andTextandCDATASectionnodes for the text. - C#. The solution loads an
XmlDocumentfrom anXmlReader. It setsPreserveWhitespaceto true, because with the default of false, "significant white space is preserved, white space is not."6 TheDtdProcessingof the reader settings isProhibit, which is already the default: "The default is Prohibit."7 With this value, the reader throws "an XmlException exception when a DTD is encountered."7 - Go. The package
encoding/xmlhas a token decoder. The solution usesDecoder.RawToken, because it keeps the prefixes of the text. "RawToken is like Decoder.Token but does not verify that start and end elements match and does not translate name space prefixes to their corresponding URLs."8 The solution therefore keeps a stack of open elements and checks each end tag. It also checks for a duplicate attribute, a second root element and text after the root, because the decoder accepts these (see Pitfalls). A token of typeDirective"represents an XML directive of the form <!text>"8, and the solution refuses it, because a document type declaration is such a directive.
All four solutions refuse a document type declaration, because entity declarations in it can read local files or make the parser use much memory (see Pitfalls).
Edge cases
The cases are in cases/basic.jsonl and cases/edge.jsonl.
declaration-and-commentandcomment-and-pi-inside: the XML declaration, comments and processing instructions are not written. The text on both sides of a comment joins, sox<!-- note -->ybecomesxy.empty-element:<item/>and<item></item>give the same output.attributes-sorted,single-quotesandattribute-whitespace: the attributes are sorted, single quotes become double quotes, and the spaces in a value are kept.escapes-in-text,escapes-in-attributeandgreater-than-in-attribute:>is escaped in text but not in a value, and"is escaped in a value but not in text.'becomes'.character-references:	 in a value stay as references, in the hexadecimal form, andABin text becomeAB.cdata: the content of a CDATA section is written as escaped text.whitespace-kept,mixed-contentandcrlf: all white space in the content is kept, and each carriage return and line feed pair becomes a line feed.non-ascii: the characters are written as themselves, so😀becomes the emoji.default-namespace,prefixes-kept,declarations-firstandinner-declaration: the prefixes of the text are kept, and the namespace declarations come before the other attributes.
cases/errors.jsonl lists the texts that each solution must refuse with parse-error: tags that do not match, a missing end tag, an empty text, two root elements, text after the root, a bare &, an entity that is not declared, a < in a value, a duplicate attribute and two texts with a document type declaration. The toolchain does not load this file yet, so each test file holds these cases by name.
Pitfalls
- Library serializers change the text. ElementTree gives its own prefixes to the namespaces, unless a program calls
register_namespace: then "Tags and attributes in this namespace will be serialized with the given prefix, if at all possible."3 Its writer also writes an element with no content as one tag by default: "If True (the default), they are emitted as a single self-closed tag, otherwise they are emitted as a pair of start/end tags."3 The minidom writer keeps the prefixes but also writes<x:item n="1"/>:
import xml.etree.ElementTree as ET
from xml.dom import minidom
text = '<x:list xmlns:x="urn:example:x"><x:item n="1"/></x:list>'
print(ET.tostring(ET.fromstring(text), encoding="unicode"))
print(minidom.parseString(text).documentElement.toxml())
print(ET.canonicalize(text))
<ns0:list xmlns:ns0="urn:example:x"><ns0:item n="1" /></ns0:list>
<x:list xmlns:x="urn:example:x"><x:item n="1"/></x:list>
<x:list xmlns:x="urn:example:x"><x:item n="1"></x:item></x:list>
All three texts are the same XML data. Compare documents in one fixed form, and not in the output of a serializer.
- Copying Go tokens.
Decoder.Tokengives each name the namespace URL inSpace: "Each of the Name structures contained in the Token has the Space set to the URL identifying its name space when known."8 AnEncoderthat writes these tokens back does not get the prefixes back:
package main
import (
"encoding/xml"
"fmt"
"io"
"strings"
)
func main() {
text := "<x:list xmlns:x=\"urn:example:x\"><x:item a=\"1\ttab\"/></x:list>"
dec := xml.NewDecoder(strings.NewReader(text))
var out strings.Builder
enc := xml.NewEncoder(&out)
for {
tok, err := dec.Token()
if err == io.EOF {
break
}
if err != nil {
fmt.Println(err)
return
}
if err := enc.EncodeToken(tok); err != nil {
fmt.Println(err)
return
}
}
enc.Flush()
fmt.Println(out.String())
}
<list xmlns="urn:example:x" xmlns:_xmlns="xmlns" _xmlns:x="urn:example:x"><item xmlns="urn:example:x" a="1	tab"></item></list>
The output also shows that the Go decoder keeps a literal tab in an attribute value. The parsers of Python and Java change it to a space, as Canonical XML expects: "Attribute values are normalized, as if by a validating processor"1. For this reason the contract has no literal tab, line feed or carriage return in a value.
- Go accepts some texts that are not XML. The decoder of
encoding/xmlreads a duplicate attribute, a second root element and text after the root with no error. BothTokenandRawTokenaccept them:
package main
import (
"encoding/xml"
"fmt"
"io"
"strings"
)
func main() {
for _, text := range []string{"<a x=\"1\" x=\"2\"/>", "<a/><b/>", "<a/>tail", "<a> </a>"} {
dec := xml.NewDecoder(strings.NewReader(text))
var err error
for err == nil {
_, err = dec.Token()
}
if err == io.EOF {
fmt.Printf("%-20q accepted\n", text)
} else {
fmt.Printf("%-20q %v\n", text, err)
}
}
}
"<a x=\"1\" x=\"2\"/>" accepted
"<a/><b/>" accepted
"<a/>tail" accepted
"<a> </a>" XML syntax error on line 1: invalid character entity
The Go solution checks these three cases itself.
- External entities. OWASP describes the attack: "XML External Entity (XXE) injection occurs when an XML processor resolves an external entity from untrusted input. This can expose local files, cause server-side request forgery (SSRF), or exhaust resources."5 The general advice is: "Disable document type definitions (DTDs) whenever possible. Reject DOCTYPE declarations if the parser supports it."5 The JDK parser with its default settings reads the file that an entity names:
import java.io.StringReader;
import java.nio.file.Files;
import java.nio.file.Path;
import javax.xml.parsers.DocumentBuilderFactory;
import org.xml.sax.InputSource;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.DefaultHandler;
public class Main {
static void parse(DocumentBuilderFactory factory, String text) throws Exception {
var builder = factory.newDocumentBuilder();
builder.setErrorHandler(new DefaultHandler());
try {
var doc = builder.parse(new InputSource(new StringReader(text)));
System.out.println("parsed: " + doc.getDocumentElement().getTextContent());
} catch (SAXParseException e) {
System.out.println("refused: " + e.getClass().getSimpleName());
}
}
public static void main(String[] args) throws Exception {
Path secret = Files.createTempFile("secret", ".txt");
Files.writeString(secret, "the content of a local file");
String text = "<!DOCTYPE a [<!ENTITY e SYSTEM \"" + secret.toUri() + "\">]><a>&e;</a>";
// The default settings read the file that the entity names.
parse(DocumentBuilderFactory.newDefaultInstance(), text);
DocumentBuilderFactory safe = DocumentBuilderFactory.newDefaultInstance();
safe.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
parse(safe, text);
Files.delete(secret);
}
}
parsed: the content of a local file
refused: SAXParseException
Python is safer by default: "By default, Expat itself does not access local files or create network connections."9 But Expat still expands the entities that a document type declaration defines, and "Expat versions lower than 2.7.2 may be vulnerable to the “billion laughs”, “quadratic blowup” and “large tokens” vulnerabilities"9. For this reason the Python solution also refuses a document type declaration. In .NET, DtdProcessing.Prohibit is the default7.
- White space in .NET. An
XmlDocumentwith the defaultPreserveWhitespaceof false drops the white space between elements6. Set it to true beforeLoad, or the output loses the line ends and the indentation of the text.
Related tasks
- Query XML with XPath finds parts of an XML document with a path.
- Read and write JSON does the same job for JSON.
- Validate data against a schema checks that a document has the structure that a schema describes.
Code
The build runs the native tests of each language in a pinned toolchain.
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/read-and-write-xml/.
from xml.dom import minidom
from xml.parsers.expat import ExpatError
class XmlError(ValueError):
"""The text is not well-formed XML, or it has a document type declaration (parse-error)."""
def __init__(self, kind: str, detail: str) -> None:
super().__init__(f"{kind}: {detail}")
self.kind = kind
def escape_text(text: str) -> str:
# & first, so that the other escapes are not escaped again.
return text.replace("&", "&").replace("<", "<").replace(">", ">").replace("\r", "
")
def escape_attribute(value: str) -> str:
value = value.replace("&", "&").replace("<", "<").replace('"', """)
# A parser turns a literal tab, line feed or carriage return in a value into a space, so these must be references.
return value.replace("\t", "	").replace("\n", "
").replace("\r", "
")
def attribute_key(name: str) -> tuple[int, str]:
# The default namespace declaration comes first, then the other declarations, then the attributes.
if name == "xmlns":
return (0, "")
if name.startswith("xmlns:"):
return (1, name)
return (2, name)
def write(node: minidom.Node, out: list[str]) -> None:
if node.nodeType in (node.TEXT_NODE, node.CDATA_SECTION_NODE):
out.append(escape_text(node.data))
elif node.nodeType == node.ELEMENT_NODE:
out.append("<" + node.tagName)
for name in sorted(node.attributes.keys(), key=attribute_key):
out.append(f' {name}="{escape_attribute(node.getAttribute(name))}"')
out.append(">")
for child in node.childNodes:
write(child, out)
out.append(f"</{node.tagName}>")
# Comments and processing instructions are not written.
def xml_rewrite(text: str) -> str:
"""Parses the XML text to a tree and writes it back in the canonical form of the contract."""
try:
doc = minidom.parseString(text)
except ExpatError as error:
raise XmlError("parse-error", str(error)) from error
# Expat does not load external entities, but it does expand the internal ones. The contract refuses both.
if doc.doctype is not None:
raise XmlError("parse-error", "a document type declaration is not allowed")
out: list[str] = []
write(doc.documentElement, out)
return "".join(out)
test_xml_rewrite.py 58 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/read-and-write-xml/.
import pytest
from xml_rewrite import XmlError, xml_rewrite
# name: (text, the canonical text)
CASES = {
"element-and-text": ("<note><to>Ada</to><body>Hello</body></note>", "<note><to>Ada</to><body>Hello</body></note>"),
"declaration-and-comment": ("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!-- a list -->\n<list><item>1</item></list>\n", "<list><item>1</item></list>"),
"empty-element": ("<list><item/><item></item></list>", "<list><item></item><item></item></list>"),
"attributes-sorted": ("<book year=\"1999\" id=\"b1\" lang=\"en\"/>", "<book id=\"b1\" lang=\"en\" year=\"1999\"></book>"),
"escapes-in-text": ("<p>Tom & Jerry <3 > 2</p>", "<p>Tom & Jerry <3 > 2</p>"),
"single-quotes": ("<a title='say \"hi\"'/>", "<a title=\"say "hi"\"></a>"),
"escapes-in-attribute": ("<a v=\"x < y & 'z'\"/>", "<a v=\"x < y & 'z'\"></a>"),
"greater-than-in-attribute": ("<a v=\"1 > 0\">2 > 1</a>", "<a v=\"1 > 0\">2 > 1</a>"),
"character-references": ("<a v=\"	 \">AB </a>", "<a v=\"	

\">AB
</a>"),
"cdata": ("<code><![CDATA[if (a < b && c) {}]]></code>", "<code>if (a < b && c) {}</code>"),
"mixed-content": ("<p>An <b>old</b> and <i>new</i> text.</p>", "<p>An <b>old</b> and <i>new</i> text.</p>"),
"whitespace-kept": ("<list>\n <item> a </item>\n</list>", "<list>\n <item> a </item>\n</list>"),
"crlf": ("<list>\r\n<item>a\r\nb</item>\r\n</list>\r\n", "<list>\n<item>a\nb</item>\n</list>"),
"attribute-whitespace": ("<a v=\" two spaces \"/>", "<a v=\" two spaces \"></a>"),
"comment-and-pi-inside": ("<a>x<!-- note -->y<?app data?>z</a>", "<a>xyz</a>"),
"non-ascii": ("<city name=\"Zürich\">東京 😀 é</city>", "<city name=\"Zürich\">東京 😀 é</city>"),
"default-namespace": ("<feed xmlns=\"urn:example:feed\"><entry/></feed>", "<feed xmlns=\"urn:example:feed\"><entry></entry></feed>"),
"prefixes-kept": ("<x:list xmlns:x=\"urn:example:x\"><x:item x:id=\"1\"/></x:list>", "<x:list xmlns:x=\"urn:example:x\"><x:item x:id=\"1\"></x:item></x:list>"),
"declarations-first": ("<r b=\"2\" xmlns:z=\"urn:z\" a=\"1\" xmlns=\"urn:d\" xmlns:m=\"urn:m\"/>", "<r xmlns=\"urn:d\" xmlns:m=\"urn:m\" xmlns:z=\"urn:z\" a=\"1\" b=\"2\"></r>"),
"inner-declaration": ("<a xmlns=\"urn:a\"><b xmlns=\"urn:b\"><c/></b></a>", "<a xmlns=\"urn:a\"><b xmlns=\"urn:b\"><c></c></b></a>"),
}
# name: text that the function must refuse
INVALID = {
"mismatched-tags": "<a><b></a></b>",
"unclosed": "<a><b></b>",
"empty-text": "",
"two-roots": "<a/><b/>",
"text-after-root": "<a/>tail",
"bare-ampersand": "<a>Tom & Jerry</a>",
"undefined-entity": "<a> </a>",
"lt-in-attribute": "<a v=\"1 < 2\"/>",
"duplicate-attribute": "<a v=\"1\" v=\"2\"/>",
"doctype": "<!DOCTYPE a [<!ENTITY e \"text\">]><a>&e;</a>",
"external-entity": "<!DOCTYPE a [<!ENTITY e SYSTEM \"file:///etc/hostname\">]><a>&e;</a>",
}
@pytest.mark.parametrize("name", CASES)
def test_cases(name: str) -> None:
text, want = CASES[name]
assert xml_rewrite(text) == want
@pytest.mark.parametrize("name", INVALID)
def test_errors(name: str) -> None:
with pytest.raises(XmlError) as info:
xml_rewrite(INVALID[name])
assert info.value.kind == "parse-error"
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-and-write-xml/.
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public final class XmlRewrite {
/** The text is not well-formed XML, or it has a document type declaration (parse-error). */
public static final class XmlException extends Exception {
private static final long serialVersionUID = 1L;
public final String kind;
XmlException(String kind, String message, Throwable cause) {
super(kind + ": " + message, cause);
this.kind = kind;
}
}
private XmlRewrite() {}
/** Parses the XML text to a tree and writes it back in the canonical form of the contract. */
public static String xmlRewrite(String text) throws XmlException {
Document doc;
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newDefaultInstance();
factory.setNamespaceAware(true);
// With this feature the parser stops at <!DOCTYPE, before it reads any entity declaration.
factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
DocumentBuilder builder = factory.newDocumentBuilder();
// The default error handler prints each fatal error to System.err; this one only throws it.
builder.setErrorHandler(new DefaultHandler());
doc = builder.parse(new InputSource(new StringReader(text)));
} catch (SAXException | IOException e) {
throw new XmlException("parse-error", e.getMessage(), e);
} catch (ParserConfigurationException e) {
throw new IllegalStateException(e);
}
StringBuilder out = new StringBuilder();
write(doc.getDocumentElement(), out);
return out.toString();
}
private static void write(Node node, StringBuilder out) {
switch (node.getNodeType()) {
// A CDATA section is a Text node too, and it is written as escaped text.
case Node.TEXT_NODE, Node.CDATA_SECTION_NODE -> escapeText(node.getNodeValue(), out);
case Node.ELEMENT_NODE -> {
Element element = (Element) node;
out.append('<').append(element.getTagName());
NamedNodeMap map = element.getAttributes();
List<Attr> attributes = new ArrayList<>();
for (int i = 0; i < map.getLength(); i++) {
attributes.add((Attr) map.item(i));
}
attributes.sort(Comparator.comparing(XmlRewrite::attributeKey));
for (Attr attribute : attributes) {
out.append(' ').append(attribute.getName()).append("=\"");
escapeAttribute(attribute.getValue(), out);
out.append('"');
}
out.append('>');
NodeList children = element.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
write(children.item(i), out);
}
out.append("</").append(element.getTagName()).append('>');
}
default -> {
// Comments and processing instructions are not written.
}
}
}
private static String attributeKey(Attr attribute) {
// The default namespace declaration comes first, then the other declarations, then the attributes.
String name = attribute.getName();
if (name.equals("xmlns")) {
return "0";
}
return (name.startsWith("xmlns:") ? "1" : "2") + name;
}
private static void escapeText(String text, StringBuilder out) {
for (int i = 0; i < text.length(); i++) {
char c = text.charAt(i);
switch (c) {
case '&' -> out.append("&");
case '<' -> out.append("<");
case '>' -> out.append(">");
case '\r' -> out.append("
");
default -> out.append(c);
}
}
}
private static void escapeAttribute(String value, StringBuilder out) {
for (int i = 0; i < value.length(); i++) {
char c = value.charAt(i);
switch (c) {
case '&' -> out.append("&");
case '<' -> out.append("<");
case '"' -> out.append(""");
// A parser turns a literal tab, line feed or carriage return in a value into a space.
case '\t' -> out.append("	");
case '\n' -> out.append("
");
case '\r' -> out.append("
");
default -> out.append(c);
}
}
}
}
XmlRewriteTest.java 85 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-and-write-xml/.
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
class XmlRewriteTest {
static Stream<Arguments> cases() {
return Stream.of(
Arguments.of("element-and-text", "<note><to>Ada</to><body>Hello</body></note>",
"<note><to>Ada</to><body>Hello</body></note>"),
Arguments.of("declaration-and-comment", "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!-- a list -->\n<list><item>1</item></list>\n",
"<list><item>1</item></list>"),
Arguments.of("empty-element", "<list><item/><item></item></list>",
"<list><item></item><item></item></list>"),
Arguments.of("attributes-sorted", "<book year=\"1999\" id=\"b1\" lang=\"en\"/>",
"<book id=\"b1\" lang=\"en\" year=\"1999\"></book>"),
Arguments.of("escapes-in-text", "<p>Tom & Jerry <3 > 2</p>",
"<p>Tom & Jerry <3 > 2</p>"),
Arguments.of("single-quotes", "<a title='say \"hi\"'/>",
"<a title=\"say "hi"\"></a>"),
Arguments.of("escapes-in-attribute", "<a v=\"x < y & 'z'\"/>",
"<a v=\"x < y & 'z'\"></a>"),
Arguments.of("greater-than-in-attribute", "<a v=\"1 > 0\">2 > 1</a>",
"<a v=\"1 > 0\">2 > 1</a>"),
Arguments.of("character-references", "<a v=\"	 \">AB </a>",
"<a v=\"	

\">AB
</a>"),
Arguments.of("cdata", "<code><![CDATA[if (a < b && c) {}]]></code>",
"<code>if (a < b && c) {}</code>"),
Arguments.of("mixed-content", "<p>An <b>old</b> and <i>new</i> text.</p>",
"<p>An <b>old</b> and <i>new</i> text.</p>"),
Arguments.of("whitespace-kept", "<list>\n <item> a </item>\n</list>",
"<list>\n <item> a </item>\n</list>"),
Arguments.of("crlf", "<list>\r\n<item>a\r\nb</item>\r\n</list>\r\n",
"<list>\n<item>a\nb</item>\n</list>"),
Arguments.of("attribute-whitespace", "<a v=\" two spaces \"/>",
"<a v=\" two spaces \"></a>"),
Arguments.of("comment-and-pi-inside", "<a>x<!-- note -->y<?app data?>z</a>",
"<a>xyz</a>"),
Arguments.of("non-ascii", "<city name=\"Zürich\">東京 😀 é</city>",
"<city name=\"Zürich\">東京 😀 é</city>"),
Arguments.of("default-namespace", "<feed xmlns=\"urn:example:feed\"><entry/></feed>",
"<feed xmlns=\"urn:example:feed\"><entry></entry></feed>"),
Arguments.of("prefixes-kept", "<x:list xmlns:x=\"urn:example:x\"><x:item x:id=\"1\"/></x:list>",
"<x:list xmlns:x=\"urn:example:x\"><x:item x:id=\"1\"></x:item></x:list>"),
Arguments.of("declarations-first", "<r b=\"2\" xmlns:z=\"urn:z\" a=\"1\" xmlns=\"urn:d\" xmlns:m=\"urn:m\"/>",
"<r xmlns=\"urn:d\" xmlns:m=\"urn:m\" xmlns:z=\"urn:z\" a=\"1\" b=\"2\"></r>"),
Arguments.of("inner-declaration", "<a xmlns=\"urn:a\"><b xmlns=\"urn:b\"><c/></b></a>",
"<a xmlns=\"urn:a\"><b xmlns=\"urn:b\"><c></c></b></a>"));
}
static Stream<Arguments> errors() {
return Stream.of(
Arguments.of("mismatched-tags", "<a><b></a></b>"),
Arguments.of("unclosed", "<a><b></b>"),
Arguments.of("empty-text", ""),
Arguments.of("two-roots", "<a/><b/>"),
Arguments.of("text-after-root", "<a/>tail"),
Arguments.of("bare-ampersand", "<a>Tom & Jerry</a>"),
Arguments.of("undefined-entity", "<a> </a>"),
Arguments.of("lt-in-attribute", "<a v=\"1 < 2\"/>"),
Arguments.of("duplicate-attribute", "<a v=\"1\" v=\"2\"/>"),
Arguments.of("doctype", "<!DOCTYPE a [<!ENTITY e \"text\">]><a>&e;</a>"),
Arguments.of("external-entity", "<!DOCTYPE a [<!ENTITY e SYSTEM \"file:///etc/hostname\">]><a>&e;</a>"));
}
@ParameterizedTest(name = "{0}")
@MethodSource("cases")
void rewrites(String name, String text, String want) throws XmlRewrite.XmlException {
assertEquals(want, XmlRewrite.xmlRewrite(text), name);
}
@ParameterizedTest(name = "{0}")
@MethodSource("errors")
void refuses(String name, String text) {
XmlRewrite.XmlException e =
assertThrows(XmlRewrite.XmlException.class, () -> XmlRewrite.xmlRewrite(text), name);
assertEquals("parse-error", e.kind, name);
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-and-write-xml/.
using System.Text;
using System.Xml;
// The text is not well-formed XML, or it has a document type declaration (parse-error).
public sealed class XmlRewriteException(string kind, Exception inner) : Exception($"{kind}: {inner.Message}", inner)
{
public string Kind { get; } = kind;
}
public static class XmlRewrite
{
// Parses the XML text to a tree and writes it back in the canonical form of the contract.
public static string Rewrite(string text)
{
// Without this, XmlDocument drops the white space between elements.
var doc = new XmlDocument { PreserveWhitespace = true };
try
{
// Prohibit is the default; it is written here so that the choice is visible.
var settings = new XmlReaderSettings { DtdProcessing = DtdProcessing.Prohibit };
using var reader = XmlReader.Create(new StringReader(text), settings);
doc.Load(reader);
}
catch (XmlException e)
{
throw new XmlRewriteException("parse-error", e);
}
var output = new StringBuilder();
Write(doc.DocumentElement!, output);
return output.ToString();
}
private static void Write(XmlNode node, StringBuilder output)
{
switch (node)
{
// Text, CDATA sections and white space are all written as escaped text.
case XmlCharacterData data when node is XmlText or XmlCDataSection or XmlWhitespace or XmlSignificantWhitespace:
EscapeText(data.Data, output);
break;
case XmlElement element:
output.Append('<').Append(element.Name);
var attributes = element.Attributes.Cast<XmlAttribute>().OrderBy(AttributeKey, StringComparer.Ordinal);
foreach (var attribute in attributes)
{
output.Append(' ').Append(attribute.Name).Append("=\"");
EscapeAttribute(attribute.Value, output);
output.Append('"');
}
output.Append('>');
foreach (XmlNode child in element.ChildNodes)
{
Write(child, output);
}
output.Append("</").Append(element.Name).Append('>');
break;
default:
// Comments and processing instructions are not written.
break;
}
}
// The default namespace declaration comes first, then the other declarations, then the attributes.
private static string AttributeKey(XmlAttribute attribute) =>
attribute.Name == "xmlns" ? "0" : (attribute.Name.StartsWith("xmlns:", StringComparison.Ordinal) ? "1" : "2") + attribute.Name;
private static void EscapeText(string text, StringBuilder output)
{
foreach (char c in text)
{
output.Append(c switch
{
'&' => "&",
'<' => "<",
'>' => ">",
'\r' => "
",
_ => c.ToString(),
});
}
}
private static void EscapeAttribute(string value, StringBuilder output)
{
foreach (char c in value)
{
output.Append(c switch
{
'&' => "&",
'<' => "<",
'"' => """,
// A parser turns a literal tab, line feed or carriage return in a value into a space.
'\t' => "	",
'\n' => "
",
'\r' => "
",
_ => c.ToString(),
});
}
}
}
XmlRewriteTests.cs 63 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-and-write-xml/.
using Xunit;
public sealed class XmlRewriteTests
{
// case, text, the canonical text
public static TheoryData<string, string, string> Cases => new()
{
{ "element-and-text", "<note><to>Ada</to><body>Hello</body></note>", "<note><to>Ada</to><body>Hello</body></note>" },
{ "declaration-and-comment", "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!-- a list -->\n<list><item>1</item></list>\n", "<list><item>1</item></list>" },
{ "empty-element", "<list><item/><item></item></list>", "<list><item></item><item></item></list>" },
{ "attributes-sorted", "<book year=\"1999\" id=\"b1\" lang=\"en\"/>", "<book id=\"b1\" lang=\"en\" year=\"1999\"></book>" },
{ "escapes-in-text", "<p>Tom & Jerry <3 > 2</p>", "<p>Tom & Jerry <3 > 2</p>" },
{ "single-quotes", "<a title='say \"hi\"'/>", "<a title=\"say "hi"\"></a>" },
{ "escapes-in-attribute", "<a v=\"x < y & 'z'\"/>", "<a v=\"x < y & 'z'\"></a>" },
{ "greater-than-in-attribute", "<a v=\"1 > 0\">2 > 1</a>", "<a v=\"1 > 0\">2 > 1</a>" },
{ "character-references", "<a v=\"	 \">AB </a>", "<a v=\"	

\">AB
</a>" },
{ "cdata", "<code><![CDATA[if (a < b && c) {}]]></code>", "<code>if (a < b && c) {}</code>" },
{ "mixed-content", "<p>An <b>old</b> and <i>new</i> text.</p>", "<p>An <b>old</b> and <i>new</i> text.</p>" },
{ "whitespace-kept", "<list>\n <item> a </item>\n</list>", "<list>\n <item> a </item>\n</list>" },
{ "crlf", "<list>\r\n<item>a\r\nb</item>\r\n</list>\r\n", "<list>\n<item>a\nb</item>\n</list>" },
{ "attribute-whitespace", "<a v=\" two spaces \"/>", "<a v=\" two spaces \"></a>" },
{ "comment-and-pi-inside", "<a>x<!-- note -->y<?app data?>z</a>", "<a>xyz</a>" },
{ "non-ascii", "<city name=\"Zürich\">東京 😀 é</city>", "<city name=\"Zürich\">東京 😀 é</city>" },
{ "default-namespace", "<feed xmlns=\"urn:example:feed\"><entry/></feed>", "<feed xmlns=\"urn:example:feed\"><entry></entry></feed>" },
{ "prefixes-kept", "<x:list xmlns:x=\"urn:example:x\"><x:item x:id=\"1\"/></x:list>", "<x:list xmlns:x=\"urn:example:x\"><x:item x:id=\"1\"></x:item></x:list>" },
{ "declarations-first", "<r b=\"2\" xmlns:z=\"urn:z\" a=\"1\" xmlns=\"urn:d\" xmlns:m=\"urn:m\"/>", "<r xmlns=\"urn:d\" xmlns:m=\"urn:m\" xmlns:z=\"urn:z\" a=\"1\" b=\"2\"></r>" },
{ "inner-declaration", "<a xmlns=\"urn:a\"><b xmlns=\"urn:b\"><c/></b></a>", "<a xmlns=\"urn:a\"><b xmlns=\"urn:b\"><c></c></b></a>" },
};
// case, text that the function must refuse
public static TheoryData<string, string> Errors => new()
{
{ "mismatched-tags", "<a><b></a></b>" },
{ "unclosed", "<a><b></b>" },
{ "empty-text", "" },
{ "two-roots", "<a/><b/>" },
{ "text-after-root", "<a/>tail" },
{ "bare-ampersand", "<a>Tom & Jerry</a>" },
{ "undefined-entity", "<a> </a>" },
{ "lt-in-attribute", "<a v=\"1 < 2\"/>" },
{ "duplicate-attribute", "<a v=\"1\" v=\"2\"/>" },
{ "doctype", "<!DOCTYPE a [<!ENTITY e \"text\">]><a>&e;</a>" },
{ "external-entity", "<!DOCTYPE a [<!ENTITY e SYSTEM \"file:///etc/hostname\">]><a>&e;</a>" },
};
[Theory]
[MemberData(nameof(Cases))]
public void Rewrites(string name, string text, string want)
{
Assert.True(want == XmlRewrite.Rewrite(text), name);
}
[Theory]
[MemberData(nameof(Errors))]
public void Refuses(string name, string text)
{
var e = Assert.Throws<XmlRewriteException>(() => XmlRewrite.Rewrite(text));
Assert.True(e.Kind == "parse-error", name);
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-and-write-xml/.
// Package xmlrewrite parses an XML text and writes it back in a canonical form.
package xmlrewrite
import (
"encoding/xml"
"errors"
"fmt"
"io"
"sort"
"strings"
)
// ErrParse is the error for a text that is not well-formed XML or that has a document type declaration.
var ErrParse = errors.New("parse-error")
// node is an element or a piece of text of the tree.
type node struct {
name string // the qualified name of an element, as in the text; empty for text
attrs []attr
children []*node
text string
}
type attr struct{ name, value string }
func qname(n xml.Name) string {
// RawToken keeps the prefix of the text in Space.
if n.Space == "" {
return n.Local
}
return n.Space + ":" + n.Local
}
// parse reads the text into a tree. RawToken keeps the prefixes, but it does not check the structure, so parse checks the end tags, the duplicate attributes and the content outside the root.
func parse(text string) (*node, error) {
dec := xml.NewDecoder(strings.NewReader(text))
var root *node
var stack []*node
for {
tok, err := dec.RawToken()
if err == io.EOF {
break
}
if err != nil {
return nil, fmt.Errorf("%w: %v", ErrParse, err)
}
switch t := tok.(type) {
case xml.StartElement:
if root != nil && len(stack) == 0 {
return nil, fmt.Errorf("%w: a second root element", ErrParse)
}
n := &node{name: qname(t.Name)}
seen := map[string]bool{}
for _, a := range t.Attr {
name := qname(a.Name)
if seen[name] {
return nil, fmt.Errorf("%w: the attribute %s occurs twice", ErrParse, name)
}
seen[name] = true
n.attrs = append(n.attrs, attr{name, a.Value})
}
if root == nil {
root = n
} else {
top := stack[len(stack)-1]
top.children = append(top.children, n)
}
stack = append(stack, n)
case xml.EndElement:
if len(stack) == 0 || stack[len(stack)-1].name != qname(t.Name) {
return nil, fmt.Errorf("%w: the end tag %s does not match", ErrParse, qname(t.Name))
}
stack = stack[:len(stack)-1]
case xml.CharData:
if len(stack) == 0 {
if strings.Trim(string(t), " \t\r\n") != "" {
return nil, fmt.Errorf("%w: text outside the root element", ErrParse)
}
continue
}
top := stack[len(stack)-1]
top.children = append(top.children, &node{text: string(t)})
case xml.Directive:
// The decoder never loads an external entity, but the contract refuses every document type declaration.
return nil, fmt.Errorf("%w: a document type declaration is not allowed", ErrParse)
}
// Comments and processing instructions are skipped.
}
if root == nil || len(stack) != 0 {
return nil, fmt.Errorf("%w: the root element is missing or not closed", ErrParse)
}
return root, nil
}
var textEscaper = strings.NewReplacer("&", "&", "<", "<", ">", ">", "\r", "
")
// A parser turns a literal tab, line feed or carriage return in a value into a space, so these must be references.
var attrEscaper = strings.NewReplacer("&", "&", "<", "<", `"`, """, "\t", "	", "\n", "
", "\r", "
")
// attrKey puts the default namespace declaration first, then the other declarations, then the attributes.
func attrKey(name string) string {
switch {
case name == "xmlns":
return "0"
case strings.HasPrefix(name, "xmlns:"):
return "1" + name
}
return "2" + name
}
func write(n *node, b *strings.Builder) {
if n.name == "" {
b.WriteString(textEscaper.Replace(n.text))
return
}
sort.Slice(n.attrs, func(i, j int) bool { return attrKey(n.attrs[i].name) < attrKey(n.attrs[j].name) })
b.WriteString("<" + n.name)
for _, a := range n.attrs {
b.WriteString(" " + a.name + `="` + attrEscaper.Replace(a.value) + `"`)
}
b.WriteString(">")
for _, c := range n.children {
write(c, b)
}
b.WriteString("</" + n.name + ">")
}
// XMLRewrite parses the XML text to a tree and writes it back in the canonical form of the contract.
func XMLRewrite(text string) (string, error) {
root, err := parse(text)
if err != nil {
return "", err
}
var b strings.Builder
write(root, &b)
return b.String(), nil
}
xml_rewrite_test.go 65 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-and-write-xml/.
package xmlrewrite
import (
"errors"
"testing"
)
func TestXMLRewrite(t *testing.T) {
cases := []struct{ name, text, want string }{
{"element-and-text", "<note><to>Ada</to><body>Hello</body></note>", "<note><to>Ada</to><body>Hello</body></note>"},
{"declaration-and-comment", "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!-- a list -->\n<list><item>1</item></list>\n", "<list><item>1</item></list>"},
{"empty-element", "<list><item/><item></item></list>", "<list><item></item><item></item></list>"},
{"attributes-sorted", "<book year=\"1999\" id=\"b1\" lang=\"en\"/>", "<book id=\"b1\" lang=\"en\" year=\"1999\"></book>"},
{"escapes-in-text", "<p>Tom & Jerry <3 > 2</p>", "<p>Tom & Jerry <3 > 2</p>"},
{"single-quotes", "<a title='say \"hi\"'/>", "<a title=\"say "hi"\"></a>"},
{"escapes-in-attribute", "<a v=\"x < y & 'z'\"/>", "<a v=\"x < y & 'z'\"></a>"},
{"greater-than-in-attribute", "<a v=\"1 > 0\">2 > 1</a>", "<a v=\"1 > 0\">2 > 1</a>"},
{"character-references", "<a v=\"	 \">AB </a>", "<a v=\"	

\">AB
</a>"},
{"cdata", "<code><![CDATA[if (a < b && c) {}]]></code>", "<code>if (a < b && c) {}</code>"},
{"mixed-content", "<p>An <b>old</b> and <i>new</i> text.</p>", "<p>An <b>old</b> and <i>new</i> text.</p>"},
{"whitespace-kept", "<list>\n <item> a </item>\n</list>", "<list>\n <item> a </item>\n</list>"},
{"crlf", "<list>\r\n<item>a\r\nb</item>\r\n</list>\r\n", "<list>\n<item>a\nb</item>\n</list>"},
{"attribute-whitespace", "<a v=\" two spaces \"/>", "<a v=\" two spaces \"></a>"},
{"comment-and-pi-inside", "<a>x<!-- note -->y<?app data?>z</a>", "<a>xyz</a>"},
{"non-ascii", "<city name=\"Zürich\">東京 😀 é</city>", "<city name=\"Zürich\">東京 😀 é</city>"},
{"default-namespace", "<feed xmlns=\"urn:example:feed\"><entry/></feed>", "<feed xmlns=\"urn:example:feed\"><entry></entry></feed>"},
{"prefixes-kept", "<x:list xmlns:x=\"urn:example:x\"><x:item x:id=\"1\"/></x:list>", "<x:list xmlns:x=\"urn:example:x\"><x:item x:id=\"1\"></x:item></x:list>"},
{"declarations-first", "<r b=\"2\" xmlns:z=\"urn:z\" a=\"1\" xmlns=\"urn:d\" xmlns:m=\"urn:m\"/>", "<r xmlns=\"urn:d\" xmlns:m=\"urn:m\" xmlns:z=\"urn:z\" a=\"1\" b=\"2\"></r>"},
{"inner-declaration", "<a xmlns=\"urn:a\"><b xmlns=\"urn:b\"><c/></b></a>", "<a xmlns=\"urn:a\"><b xmlns=\"urn:b\"><c></c></b></a>"},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
got, err := XMLRewrite(c.text)
if err != nil || got != c.want {
t.Errorf("XMLRewrite(%q) = %q, %v; want %q, nil", c.text, got, err, c.want)
}
})
}
}
func TestXMLRewriteRefuses(t *testing.T) {
invalid := []struct{ name, text string }{
{"mismatched-tags", "<a><b></a></b>"},
{"unclosed", "<a><b></b>"},
{"empty-text", ""},
{"two-roots", "<a/><b/>"},
{"text-after-root", "<a/>tail"},
{"bare-ampersand", "<a>Tom & Jerry</a>"},
{"undefined-entity", "<a> </a>"},
{"lt-in-attribute", "<a v=\"1 < 2\"/>"},
{"duplicate-attribute", "<a v=\"1\" v=\"2\"/>"},
{"doctype", "<!DOCTYPE a [<!ENTITY e \"text\">]><a>&e;</a>"},
{"external-entity", "<!DOCTYPE a [<!ENTITY e SYSTEM \"file:///etc/hostname\">]><a>&e;</a>"},
}
for _, c := range invalid {
t.Run(c.name, func(t *testing.T) {
if got, err := XMLRewrite(c.text); !errors.Is(err, ErrParse) {
t.Errorf("XMLRewrite(%q) = %q, %v; want a parse-error", c.text, got, err)
}
})
}
}
References
- RFC 3076, Canonical XML Version 1.0, J. Boyer, March 2001, Abstract; 1.1 Terminology; 2.2 Document Order; 2.3 Processing Model
- The Python Standard Library, xml.dom.minidom, Python 3.14, parseString; Node.toxml
- The Python Standard Library, xml.etree.ElementTree, Python 3.14, canonicalize; register_namespace; ElementTree.write (short_empty_elements)
- Java SE 25 API, javax.xml.parsers.DocumentBuilderFactory, newDefaultInstance; setFeature; setNamespaceAware
- OWASP Cheat Sheet Series, XML External Entity Prevention Cheat Sheet, Introduction; General Guidance; Java, DocumentBuilderFactory (DOM)
- .NET API documentation, XmlDocument.PreserveWhitespace Property, Property Value; Remarks
- .NET API documentation, XmlReaderSettings.DtdProcessing Property, Property Value; Remarks
- Go standard library, package encoding/xml, Decoder.RawToken; Decoder.Strict; Directive; Encoder.EncodeToken
- The Python Standard Library, XML Processing Modules, Python 3.14, XML security
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (csharp) | I0 not checked yet |
|
| Code (go) | I0 not checked yet |
|
| Code (java) | I0 not checked yet |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag WXK4C9 Edit this page History Report an error Markdown