DOM Parsing and Serialization (original) (raw)
Abstract
This specification defines APIs for the parsing and serializing of HTML and XML-based DOM nodes for web applications.
Status of This Document
This section describes the status of this document at the time of its publication. A list of current W3C publications and the latest revision of this technical report can be found in the W3C technical reports index at https://www.w3.org/TR/.
This document was published by the Web Applications Working Group as an Editor's Draft.
Publication as an Editor's Draft does not imply endorsement by W3C and its Members.
This is a draft document and may be updated, replaced or obsoleted by other documents at any time. It is inappropriate to cite this document as other than work in progress.
This document was produced by a group operating under theW3C Patent Policy.W3C maintains apublic list of any patent disclosures made in connection with the deliverables of the group; that page also includes instructions for disclosing a patent. An individual who has actual knowledge of a patent which the individual believes containsEssential Claim(s) must disclose the information in accordance withsection 6 of the W3C Patent Policy.
This document is governed by the03 November 2023 W3C Process Document.
Table of Contents
- Abstract
- Status of This Document
- Candidate Recommendation Exit Criteria
- Extensibility
- 1. Introduction
- 2. APIs for parsing and serializing DOM
- 3. Algorithms for parsing and serializing
- 3.1 Parsing
- 3.2 Serializing
- 3.2.1 XML Serialization
1. 3.2.1.1 XML serializing an Element node
1. 3.2.1.1.1 Recording the namespace
2. 3.2.1.1.2 The Namespace Prefix Map
3. 3.2.1.1.3 Serializing an Element's attributes
4. 3.2.1.1.4 Generating namespace prefixes
2. 3.2.1.2 XML serializing a Document node
3. 3.2.1.3 XML serializing a Comment node
4. 3.2.1.4 XML serializing a Text node
5. 3.2.1.5 XML serializing a DocumentFragment node
6. 3.2.1.6 XML serializing a DocumentType node
7. 3.2.1.7 XML serializing a ProcessingInstruction node
- 3.2.1 XML Serialization
- A. Dependencies
- B. Revision History
- C. Acknowledgements
- D. References
- D.1 Normative references
This specification will not advance to Proposed Recommendation before the spec'stest suite is completed and two or more independent implementations pass each test, although no single implementation must pass each test. We expect to meet this criteria no sooner than 24 October 2014. The group will also create anImplementation Report.
Conformance
As well as sections marked as non-normative, all authoring guidelines, diagrams, examples, and notes in this specification are non-normative. Everything else in this specification is normative.
The IDL fragments in this specification must be interpreted as required for conforming IDL fragments, as described in the Web IDL specification. [WEBIDL]
Requirements phrased in the imperative as part of algorithms (such as "strip any leading space characters" or "return false and terminate these steps") are to be interpreted with the meaning of the key word ("must", "should", "may", etc) used in introducing the algorithm.
Conformance requirements phrased as algorithms or specific steps may be implemented in any manner, so long as the end result is equivalent. (In particular, the algorithms defined in this specification are intended to be easy to follow, and not intended to be performant.)
User agents may impose implementation-specific limits on otherwise unconstrained inputs, e.g. to prevent denial of service attacks, to guard against running out of memory, or to work around platform-specific limitations.
When a method or an attribute is said to call another method or attribute, the user agent must invoke its internal API for that attribute or method so that e.g. the author can't change the behavior by overriding attributes or methods with custom properties or functions in ECMAScript. [ECMA-262]
Unless otherwise stated, string comparisons are done in a case-sensitive manner.
If an algorithm calls into another algorithm, any exception that is thrown by the latter (unless it is explicitly caught), must cause the former to terminate, and the exception to be propagated up to its caller.
Vendor-specific proprietary extensions to this specification are strongly discouraged. Authors must not use such extensions, as doing so reduces interoperability and fragments the user base, allowing only users of specific user agents to access the content in question.
If vendor-specific extensions are needed, the members should be prefixed by vendor-specific strings to prevent clashes with future versions of this specification. Extensions must be defined so that the use of extensions neither contradicts nor causes the non-conformance of functionality defined in the specification.
When vendor-neutral extensions to this specification are needed, either this specification can be updated accordingly, or an extension specification can be written that overrides the requirements in this specification. Such an extension specification becomes anapplicable specification for the purposes of conformance requirements in this specification.
A document object model (DOM) is an in-memory representation of various types of Nodes where each Node is connected in a tree. The [HTML5] and [DOM4] specifications describe DOM and its Nodes is greater detail.
Parsing is the term used for converting a string representation of a DOM into an actual DOM, and Serializing is the term used to transform a DOM back into a string. This specification concerns itself with defining various APIs for both parsing and serializing a DOM.
For example: the innerHTML API is a common way to both parse and serialize a DOM (it does both). If a particular Node, has the following in-memory DOM:
HTMLDivElement (nodeName: "div")
┃
┣━ HTMLSpanElement (nodeName: "span")
┃ ┃
┃ ┗━ Text (data: "some ")
┃
┗━ HTMLElement (nodeName: "em")
┃
┗━ Text (data: "text!")
And the HTMLDivElement
node is stored in a variable myDiv
, then to serialize myDiv
's children simply get (read) theElement's innerHTML property (this triggers the serialization):
var serializedChildren = myDiv.innerHTML;
// serializedChildren has the value:
// "<span>some </span><em>text!</em>"
To parse new children for myDiv
from a string (replacing its existing children), simply set the innerHTML property (this triggers parsing of the assigned string):
myDiv.innerHTML = "<span>new</span><em>children!</em>";
This specification describes two flavors of parsing and serializing: HTML and XML (with XHTML being a type of XML). Each follows the rules of its respective markup language. The above example shows HTML parsing and serialization. The specific algorithms for HTML parsing and serializing are defined in the [HTML5] specification. This specification contains the algorithm for XML serializing. The grammar for XML parsing is described in the [XML10] specification.
Round-tripping a DOM means to serialize and then immediately parse the serialized string back into a DOM. Ideally, this process does not result in any data loss with respect to the identity and attributes of the Node in the DOM.Round-tripping is especially tricky for an XML serialization, which must be concerned with preserving the Node's namespace identity in the serialization (wereas namespaces are ignored in HTML).
Consider the XML serialization of the following in-memory DOM:
Element (nodeName: "root")
┃
┗━ HTMLScriptElement (nodeName: "script")
┃
┗━ Text (data: "alert('hello world')")
An XML serialization must include the HTMLScriptElement
Node'snamespace in order to preserve the identity of thescript
element, and to allow the serialized string toround-trip through an XML parser. Assuming that root
is in a variable named root
:
var xmlSerialization = new XMLSerializer().serializeToString(root);
// xmlSerialization has the value:
// "<root><script xmlns="http://www.w3.org/1999/xhtml">alert('hello world')</script></root>"
The term context object means the object on which the API being discussed was called.
The following terms are understood to represent their respective namespaces in this specification (and makes it easier to read):
- The HTML namespace is
http://www.w3.org/1999/xhtml
- The XML namespace is
http://www.w3.org/XML/1998/namespace
- The XMLNS namespace is
http://www.w3.org/2000/xmlns/
The definition of DOMParser
has moved to the HTML Standard.
The definition of XMLSerializer
has moved to the HTML Standard.
The definition of InnerHTML
has moved to the HTML Standard.
The definition of outerHTML
has moved to the HTML Standard.
The definition of insertAdjacentHTML
has moved to the HTML Standard.
The definition of createContextualFragment
has moved to the HTML Standard.
The definition of fragment parsing algorithm
has moved to the HTML Standard.
The definition of fragment serializing algorithm
has moved to the HTML Standard.
An XML serialization differs from an HTML serialization in the following ways:
- Elements and attributes will always be serialized such that their
namespaceURI
is preserved. In some cases this means that an existingprefix
, prefix declaration attribute or default namespace declaration attribute might be dropped, substituted or changed. An HTML serialization does not attempt to preserve thenamespaceURI
. - Elements not in the HTML namespace containing no children, are serialized using the empty-element tag syntax (i.e., according to the XMLEmptyElemTag production).
Otherwise, the algorithm for producing an XML serialization is designed to produce a serialization that is compatible with the HTML parser. For example, elements in theHTML namespace that contain no child nodes are serialized with an explicit begin and end tag rather than using the empty-element tag syntax.
Note
Per [DOM4], [Attr](#dfn-attribute)
objects do not inherit from Node, and thus cannot be serialized by the XML serialization algorithm. An attempt to serialize anAttr object will result in an empty string.
To produce an XML serialization of a [Node](#dfn-node)
node given a flag require well-formed, run the following steps:
- Let namespace be a context namespace with value
null
. The context namespace tracks the XML serialization algorithm's current default namespace. The context namespace is changed when either an Element Node has a default namespace declaration, or the algorithm generates a default namespace declaration for the Element Node to match its own namespace. The algorithm assumes no namespace (null
) to start. - Let prefix map be a new namespace prefix map.
- Add the XML namespace with prefix value "
xml
" toprefix map. - Let prefix index be a generated namespace prefix index with value
1
. The generated namespace prefix index is used to generate a new unique prefix value when no suitable existing namespace prefix is available to serialize anode'snamespaceURI
(or thenamespaceURI
of one ofnode's attributes). See the generate a prefix algorithm. - Return the result of running the XML serialization algorithm on node passing the context namespace namespace, namespace prefix map prefix map, generated namespace prefix index reference toprefix index, and the flag require well-formed. If anexception occurs during the execution of the algorithm, then catch that exception and throw an "
[InvalidStateError](#dfn-invalidstateerror)
"[DOMException](#dfn-domexception)
.
Each of the following algorithms for producing an XML serialization of a DOM node take as input a node to serialize and the following arguments:
- A context namespace namespace
- A namespace prefix map prefix map
- A generated namespace prefix index prefix index
- The require well-formed flag
The XML serialization algorithm produces an XML serialization of an arbitrary DOM node node based on the node's interface type. Each referenced algorithm is to be passed the arguments as they were recieved by the caller and return their result to the caller. Re-throw any exceptions. If node's interface is:
[Element](#dfn-element)
Run the algorithm for XML serializing an Element node node.
[Document](#dfn-document)
Run the algorithm for XML serializing a Document node node.
[Comment](#dfn-comment)
Run the algorithm for XML serializing a Comment node node.
[Text](#dfn-text)
Run the algorithm for XML serializing a Text node node.
[DocumentFragment](#dfn-documentfragment)
Run the algorithm for XML serializing a DocumentFragment node node.
[DocumentType](#dfn-documenttype)
Run the algorithm for XML serializing a DocumentType node node.
[ProcessingInstruction](#dfn-processinginstruction)
Run the algorithm for XML serializing a ProcessingInstruction node node.
An [Attr](#dfn-attribute)
object
Return an empty string.
Anything else
Throw a TypeError. Only Nodes and Attr objects can be serialized by this algorithm.
Each of the above referenced algorithms are detailed in the sections that follow.
The algorithm for producing an XML serialization of a DOM node of type Element is as follows:
- If the require well-formed flag is set (its value is
true
), and this node's[localName](#dfn-localname)
attribute contains the character ":
" (U+003A COLON) or does not match the XML Name production, thenthrow an exception; the serialization of this node would not be a well-formed element. - Let markup be the string "
<
" (U+003C LESS-THAN SIGN). - Let qualified name be an empty string.
- Let skip end tag be a boolean flag with value
false
. - Let ignore namespace definition attribute be a boolean flag with value
false
. - Given prefix map, copy a namespace prefix map and letmap be the result.
- Let local prefixes map be an empty map. The map has unique Node
prefix
strings as its keys, with correspondingnamespaceURI
Node values as the map's key values (in this map, thenull
namespace is represented by the empty string).
Note
This map is local to each element. It is used to ensure there are no conflicting prefixes should a new namespaceprefix
attribute need to begenerated. It is also used to enable skipping of duplicate prefix definitions whenwriting an element's attributes: the map allows the algorithm to distinguish between aprefix
in thenamespace prefix map that might be locally-defined (to the current Element) and one that is not. - Let local default namespace be the result ofrecording the namespace information for node given map andlocal prefixes map.
Note
The above step will update map with any found namespace prefix definitions, add the found prefix definitions to the local prefixes map and return a local default namespace value defined by a default namespace attribute if one exists. Otherwise it returnsnull
. - Let inherited ns be a copy of namespace.
- Let ns be the value of node's
[namespaceURI](#dfn-namespaceuri)
attribute. - If inherited ns is equal to ns, then:
- If local default namespace is not
null
, then setignore namespace definition attribute totrue
. - If ns is the XML namespace, then append toqualified name the concatenation of the string "
xml:
" and the value of node's[localName](#dfn-localname)
. - Otherwise, append to qualified name the value of node's
[localName](#dfn-localname)
. The node's[prefix](#dfn-prefix)
if it exists, is dropped. - Append the value of qualified name to markup.
- Otherwise, inherited ns is not equal to ns (the node's own namespace is different from the context namespace of its parent). Run these sub-steps:
- Let prefix be the value of node's
[prefix](#dfn-prefix)
attribute. - Let candidate prefix be the result ofretrieving a preferred prefix string prefix from map given namespace ns.
Note
The above may returnnull
if no namespace key ns exists in map. - If the value of prefix matches "
xmlns
", then run the following steps:- If the require well-formed flag is set, then throw an error. AnElement with
[prefix](#dfn-prefix)
"xmlns
" will not legally round-trip in a conforming XML parser. - Let candidate prefix be the value of prefix.
- If the require well-formed flag is set, then throw an error. AnElement with
- Found a suitable namespace prefix: if candidate prefix is not
null
(a namespace prefix is defined which maps to ns), then:
Note
The following may serialize a different[prefix](#dfn-prefix)
than the Element's existing[prefix](#dfn-prefix)
if it already had one. However, theretrieving a preferred prefix string algorithm already tried to match the existing prefix if possible.- Append to qualified name the concatenation ofcandidate prefix, "
:
" (U+003A COLON), and node's[localName](#dfn-localname)
. There exists on this node or thenode's ancestry a namespace prefix definition that defines the node's namespace. - If the local default namespace is not
null
(there exists a locally-defined default namespace declaration attribute) and its value is not theXML namespace, then let inherited ns get the value oflocal default namespace unless thelocal default namespace is the empty string in which case let it getnull
(the context namespace is changed to the declared default, rather than this node's own namespace).
Note
Any default namespace definitions or namespace prefixes that define theXML namespace are omitted when serializing this node's attributes. - Append the value of qualified name to markup.
- Append to qualified name the concatenation ofcandidate prefix, "
- Otherwise, if prefix is not
null
, then:
Note
By this step, there is no namespace or prefix mapping declaration in thisnode (or any parent node visited by this algorithm) that definesprefix otherwise the step labelled Found a suitable namespace prefix would have been followed. The sub-steps that follow will create a new namespace prefix declaration for prefix and ensure that prefix does not conflict with an existing namespace prefix declaration of the samelocalName
in node'sattribute list.- If the local prefixes map contains a key matching prefix, then let prefix be the result of generating a prefix providing as inputmap, ns, and prefix index.
- Add prefix to map given namespace ns.
- Append to qualified name the concatenation of prefix, "
:
" (U+003A COLON), and node's[localName](#dfn-localname)
. - Append the value of qualified name to markup.
- Append the following to markup, in the order listed:
Note
The following serializes a namespace prefix declaration for prefix which was just added to the map.
1. "
2. The string "xmlns:
";
3. The value of prefix;
4. "="
" (U+003D EQUALS SIGN, U+0022 QUOTATION MARK);
5. The result of serializing an attribute value given ns and therequire well-formed flag as input;
6. ""
" (U+0022 QUOTATION MARK).
7. If local default namespace is notnull
(there exists a locally-defined default namespace declaration attribute), then letinherited ns get the value of local default namespace unless the local default namespace is the empty string in which case let it getnull
.
- Otherwise, if local default namespace is
null
, orlocal default namespace is notnull
and its value is not equal to ns, then:
Note
At this point, the namespace for this node still needs to be serialized, but there's noprefix
(or candidate prefix) availble; the following uses the default namespace declaration to define the namespace--optionally replacing an existing default declaration if present.- Set the ignore namespace definition attribute flag to
true
. - Append to qualified name the value of node's
[localName](#dfn-localname)
. - Let the value of inherited ns be ns.
Note
The new default namespace will be used in the serialization to define thisnode's namespace and act as the context namespace for itschildren. - Append the value of qualified name to markup.
- Append the following to markup, in the order listed:
Note
The following serializes the new (or replacement) default namespace definition.
1. "
2. The string "xmlns
";
3. "="
" (U+003D EQUALS SIGN, U+0022 QUOTATION MARK);
4. The result of serializing an attribute value given ns and therequire well-formed flag as input;
5. ""
" (U+0022 QUOTATION MARK).
- Set the ignore namespace definition attribute flag to
- Otherwise, the node has a local default namespace that matchesns. Append to qualified name the value of node's
[localName](#dfn-localname)
, let the value of inherited ns be ns, and append the value of qualified name to markup.
Note
All of the combinations where ns is not equal toinherited ns are handled above such that node will be serialized preserving its original[namespaceURI](#dfn-namespaceuri)
. - Append to markup the result of theXML serialization of node's attributes given map, prefix index, local prefixes map,ignore namespace definition attribute flag, andrequire well-formed flag.
- If ns is the HTML namespace, and the node's list ofchildren is empty, and the node's
[localName](#dfn-localname)
matches any one of the following void elements: "area
", "base
", "basefont
", "bgsound
", "br
", "col
", "embed
", "frame
", "hr
", "img
", "input
", "keygen
", "link
", "menuitem
", "meta
", "param
", "source
", "track
", "wbr
"; then append the following to markup, in the order listed: - "
- "
/
" (U+002F SOLIDUS).
and set the skip end tag flag totrue
. - If ns is not the HTML namespace, and the node's list ofchildren is empty, then append "
/
" (U+002F SOLIDUS) to markup and set the skip end tag flag totrue
. - Append "
>
" (U+003E GREATER-THAN SIGN) to markup. - If the value of skip end tag is
true
, then return the value ofmarkup and skip the remaining steps. The node is a leaf-node. - If ns is the HTML namespace, and the node's
[localName](#dfn-localname)
matches the string "template
", then this is a[template](#dfn-template)
element. Append to markup the result ofXML serializing a DocumentFragment node given the template element'stemplate contents (a[DocumentFragment](#dfn-documentfragment)
), providinginherited ns, map, prefix index, and therequire well-formed flag.
Note
This allows template content to round-trip , given the rules forparsing XHTML documents. - Otherwise, append to markup the result of running theXML serialization algorithm on each of node's children, intree order, providing inherited ns, map,prefix index, and the require well-formed flag.
- Append the following to markup, in the order listed:
- "
</
" (U+003C LESS-THAN SIGN, U+002F SOLIDUS); - The value of qualified name;
- "
>
" (U+003E GREATER-THAN SIGN). - Return the value of markup.
This following algorithm will update the namespace prefix map with any found namespace prefix definitions, add the found prefix definitions to the local prefixes map, and return a local default namespace value defined by a default namespace attribute if one exists. Otherwise it returns null
.
When recording the namespace information for an [Element](#dfn-element)
element, given a namespace prefix map map and alocal prefixes map (initially empty), the user agent must run the following steps:
- Let default namespace attr value be
null
. - Main: For each attribute attr in element's
[attributes](#dfn-attributes)
, in the order they are specified in the element'sattribute list:
Note
The following conditional steps find namespace prefixes. Only attributes in the XMLNS namespace are considered (e.g., attributes made to look like namespace declarations via[setAttribute](#dfn-setattribute)(_"xmlns:pretend-prefix"_,_"pretend-namespace"_)
are not included).- Let attribute namespace be the value of attr's
[namespaceURI](#dfn-namespaceuri)
value. - Let attribute prefix be the value of attr's
[prefix](#dfn-prefix)
. - If the attribute namespace is the XMLNS namespace, then:
- If attribute prefix is
null
, then attr is a default namespace declaration. Set the default namespace attr value to attr's[value](#dfn-value)
and stop running these steps, returning to Main to visit the next attribute. - Otherwise, the attribute prefix is not
null
and attr is a namespace prefix definition. Run the following steps:
1. Let prefix definition be the value of attr's[localName](#dfn-attr-localname)
.
2. Let namespace definition be the value of attr's[value](#dfn-value)
.
3. If namespace definition is the XML namespace, then stop running these steps, and return to Main to visit the next attribute.
Note
XML namespace definitions in prefixes are completely ignored (in order to avoid unnecessary work when there might be prefix conflicts).XML namespaced elements are always handled uniformly by prefixing (and overriding if necessary) the element's localname with the reserved "xml
" prefix.
4. If namespace definition is the empty string (the declarative form of having no namespace), then let namespace definition benull
instead.
5. If prefix definition is found in map given the namespacenamespace definition, then stop running these steps, and return to Main to visit the next attribute.
Note
This step avoids adding duplicate prefix definitions for the same namespace in the map. This has the side-effect of avoiding later serialization of duplicate namespace prefix declarations in any descendant nodes.
6. Add the prefix prefix definition to map given namespacenamespace definition.
7. Add the value of prefix definition as a new key to thelocal prefixes map, with the namespace definition as the key's value replacing the value ofnull
with the empty string if applicable.
- If attribute prefix is
- Let attribute namespace be the value of attr's
- Return the value of default namespace attr value.
Note
The empty string is a legitimate return value and is not converted tonull
.
A namespace prefix map is a map that associates namespaceURI
andnamespace prefix lists, where namespaceURI
values are the map's unique keys (which can include the null
value representing no namespace), and ordered lists of associated prefix
values are the map's key values. Thenamespace prefix map will be populated by previously seen namespaceURIs and all their previously encountered prefix associations for a given node and its ancestors.
Note
Note: the last seen prefix
for a givennamespaceURI
is at the end of its respective list. The list is searched to find potentially matching prefixes, and if no matches are found for the givennamespaceURI
, then the last prefix
in the list is used. Seecopy a namespace prefix map and retrieve a preferred prefix string for additional details.
To copy a namespace prefix map map means to copy the map's keys into a new empty namespace prefix map, and to copy each of the values in thenamespace prefix list associated with each keys' value into a newlist which should be associated with the respective key in the new map.
To retrieve a preferred prefix string preferred prefix from the namespace prefix map map given a namespacens, the user agent should:
- Let candidates list be the result of retrieving a list from map where there exists a key in map that matches the value of ns or if there is no such key, then stop running these steps, and return the
null
value. - Otherwise, for each prefix value prefix in candidates list, iterating from beginning to end:
Note
There will always be at least one prefix value in the list.- If prefix matches preferred prefix, then stop running these steps and return prefix.
- If prefix is the last item in the candidates list, then stop running these steps and return prefix.
To check if a prefix string prefix is found in anamespace prefix map map given a namespace ns, the user agent should:
- Let candidates list be the result of retrieving a list from map where there exists a key in map that matches the value of ns or if there is no such key, then stop running these steps, and return
false
. - If the value of prefix occurs at least once in candidates list, return
true
, otherwise returnfalse
.
To add a prefix string prefix to the namespace prefix map map given a namespace ns, the user agent should:
- Let candidates list be the result of retrieving a list from map where there exists a key in map that matches the value of ns or if there is no such key, then let candidates list be
null
. - If candidates list is
null
, then create a new list withprefix as the only item in the list, and associate that list with a new key ns in map. - Otherwise, append prefix to the end of candidates list.
Note
The steps in retrieve a preferred prefix string use the list to track the most recently used (MRU) prefix associated with a given namespace, which will be the prefix at the end of the list. This list may contain duplicates of the same prefix value seen earlier (and that's OK).
The XML serialization of the attributes of an [Element](#dfn-element)
element together with a namespace prefix map map, agenerated namespace prefix index prefix index reference, alocal prefixes map, a ignore namespace definition attribute flag, and arequire well-formed flag, is the result of the following algorithm:
- Let result be the empty string.
- Let localname set be a new empty namespace localname set. Thislocalname set will contain tuples of unique attribute
[namespaceURI](#dfn-namespaceuri)
and[localName](#dfn-localname)
pairs, and is populated as each attr is processed. This set is used to [optionally] enforce the well-formed constraint that an element cannot have two attributes with the same[namespaceURI](#dfn-namespaceuri)
and[localName](#dfn-localname)
. This can occur when two otherwise identical attributes on the same element differ only by their prefix values. - Loop: For each attribute attr in element's
[attributes](#dfn-attributes)
, in the order they are specified in the element'sattribute list:- If the require well-formed flag is set (its value is
true
), and thelocalname set contains a tuple whose values match those of a new tuple consisting of attr's[namespaceURI](#dfn-namespaceuri)
attribute and[localName](#dfn-localname)
attribute, then throw an exception; the serialization of this attr would fail to produce a well-formed element serialization. - Create a new tuple consisting of attr's
[namespaceURI](#dfn-namespaceuri)
attribute and[localName](#dfn-localname)
attribute, and add it to thelocalname set. - Let attribute namespace be the value of attr's
[namespaceURI](#dfn-namespaceuri)
value. - Let candidate prefix be
null
. - If attribute namespace is not
null
, then run these sub-steps:- Let candidate prefix be the result ofretrieving a preferred prefix string from map given namespaceattribute namespace with preferred prefix being attr's
[prefix](#dfn-prefix)
value. - If the value of attribute namespace is the XMLNS namespace, then run these steps:
1. If any of the following are true, then stop running these steps and goto Loop to visit the next attribute:
* the attr's[value](#dfn-value)
is the XML namespace;
Note
The XML namespace cannot be redeclared and surviveround-tripping (unless it defines the prefix "xml
"). To avoid this problem, this algorithm always prefixes elements in the XML namespace with "xml
" and drops any related definitions as seen in the above condition.
* the attr's[prefix](#dfn-prefix)
isnull
and theignore namespace definition attribute flag istrue
(theElement's default namespace attribute should be skipped);
* the attr's[prefix](#dfn-prefix)
is notnull
and either
* the attr's[localName](#dfn-attr-localname)
is not a key contained in the local prefixes map, or
* the attr's[localName](#dfn-attr-localname)
is present in the local prefixes map but the value of the key does not matchattr's[value](#dfn-value)
and furthermore that the attr's[localName](#dfn-attr-localname)
(as the prefix to find) is found in the namespace prefix map given the namespace consisting of the attr's[value](#dfn-value)
(the current namespace prefix definition was exactly defined previously--on an ancestor element not the current element whose attributes are being processed).
2. If the require well-formed flag is set (its value istrue
), and the value of attr's[value](#dfn-value)
attribute matches theXMLNS namespace, then throw an exception; the serialization of this attribute would produce invalid XML because the XMLNS namespace is reserved and cannot be applied as an element's namespace via XML parsing.
Note
DOM APIs do allow creation of elements in the XMLNS namespace but with strict qualifications.
3. If the require well-formed flag is set (its value istrue
), and the value of attr's[value](#dfn-value)
attribute is the empty string, then throw an exception; namespace prefix declarations cannot be used to undeclare a namespace (use a default namespace declaration instead).
4. the attr's[prefix](#dfn-prefix)
matches the string "xmlns
", then let candidate prefix be the string "xmlns
". - Otherwise, the attribute namespace in not the XMLNS namespace. Run these steps:
1. Let candidate prefix be the result of generating a prefix providingmap, attribute namespace, and prefix index as input.
2. Append the following to result, in the order listed:
1. "
2. The string "xmlns:
";
3. The value of candidate prefix;
4. "="
" (U+003D EQUALS SIGN, U+0022 QUOTATION MARK);
5. The result of serializing an attribute value given attribute namespace and the require well-formed flag as input;
6. ""
" (U+0022 QUOTATION MARK).
- Let candidate prefix be the result ofretrieving a preferred prefix string from map given namespaceattribute namespace with preferred prefix being attr's
- Append a "
- If candidate prefix is not
null
, then append to result the concatenation of candidate prefix with ":
" (U+003A COLON). - If the require well-formed flag is set (its value is
true
), and thisattr's[localName](#dfn-localname)
attribute contains the character ":
" (U+003A COLON) or does not match the XML Name production or equals "xmlns
" and attribute namespace isnull
, thenthrow an exception; the serialization of this attr would not be a well-formed attribute. - Append the following strings to result, in the order listed:
- The value of attr's
[localName](#dfn-attr-localname)
; - "
="
" (U+003D EQUALS SIGN, U+0022 QUOTATION MARK); - The result of serializing an attribute value given attr's
[value](#dfn-value)
attribute and the require well-formed flag as input; - "
"
" (U+0022 QUOTATION MARK).
- The value of attr's
- If the require well-formed flag is set (its value is
- Return the value of result.
When serializing an attribute value given an attribute value andrequire well-formed flag, the user agent must run the following steps:
- If the require well-formed flag is set (its value is
true
), andattribute value contains characters that are not matched by the XML Char production, then throw an exception; the serialization of this attribute value would fail to produce a well-formed element serialization. - If attribute value is
null
, then return the empty string. - Otherwise, attribute value is a string. Return the value ofattribute value, first replacing any occurrences of the following:
- "
&
" with "&
" - "
"
" with ""
" - "
<
" with "<
" - "
>
" with ">
"
Note
This matches behavior present in browsers, and goes above and beyond the grammar requirement in the XML specification's AttValue production by also replacing ">
" characters.
- "
To generate a prefix given anamespace prefix map map, a string new namespace, and a reference to a generated namespace prefix index prefix index, the user agent must run the following steps:
- Let generated prefix be the concatenation of the string "
ns
" and the current numerical value of prefix index. - Let the value of prefix index be incremented by one.
- Add to map the generated prefix given thenew namespace namespace.
- Return the value of generated prefix.
The algorithm for producing an XML serialization of a DOM node of type Document is as follows:
If the require well-formed flag is set (its value is true
), and thisnode has no [documentElement](#dfn-documentelement)
(the[documentElement](#dfn-documentelement)
attribute's value is null
), thenthrow an exception; the serialization of this node would not be a well-formed document.
Otherwise, run the following steps:
- Let serialized document be an empty string.
- For each child child of node, in tree order, run theXML serialization algorithm on the child passing along the provided arguments, and append the result to serialized document.
Note
This will serialize any number of ProcessingInstruction and Comment nodes both before and after the Document's documentElement node, including at most one DocumentType node. (Text nodes are not allowed as children of theDocument.) - Return the value of serialized document.
The algorithm for producing an XML serialization of a DOM node of type Text is as follows:
- If the require well-formed flag is set (its value is
true
), andnode's[data](#dfn-data)
contains characters that are not matched by the XMLChar production, then throw an exception; the serialization of thisnode's[data](#dfn-data)
would not be well-formed. - Let markup be the value of node's
[data](#dfn-data)
. - Replace any occurrences of "
&
" in markup by "&
". - Replace any occurrences of "
<
" in markup by "<
". - Replace any occurrences of "
>
" in markup by ">
". - Return the value of markup.
The algorithm for producing an XML serialization of a DOM node of typeDocumentFragment is as follows:
- Let markup the empty string.
- For each child child of node, in tree order, run theXML serialization algorithm on the child given namespace,prefix map, a reference to prefix index, and flagrequire well-formed. Concatenate the result to markup.
- Return the value of markup.
The algorithm for producing an XML serialization of a DOM node of type DocumentType is as follows:
- If the require well-formed flag is
true
and the node's[publicId](#dfn-publicid)
attribute contains characters that are not matched by the XMLPubidChar production, then throw an exception; the serialization of thisnode would not be a well-formed document type declaration. - If the require well-formed flag is
true
and the node's[systemId](#dfn-systemid)
attribute contains characters that are not matched by the XMLChar production or that contains both a ""
" (U+0022 QUOTATION MARK) and a "'
" (U+0027 APOSTROPHE), then throw an exception; the serialization of thisnode would not be a well-formed document type declaration. - Let markup be an empty string.
- Append the string "
<!DOCTYPE
" to markup. - Append "
- Append the value of the node's
[name](#dfn-doctype-name)
attribute to markup. For a node belonging to an HTML document, the value will be all lowercase. - If the node's
[publicId](#dfn-publicid)
is not the empty string then append the following, in the order listed, to markup:- "
- The string "
PUBLIC
"; - "
- "
"
" (U+0022 QUOTATION MARK); - The value of the node's
[publicId](#dfn-publicid)
attribute; - "
"
" (U+0022 QUOTATION MARK).
- "
- If the node's
[systemId](#dfn-systemid)
is not the empty string and thenode's[publicId](#dfn-publicid)
is set to the empty string, then append the following, in the order listed, to markup:- "
- The string "
SYSTEM
".
- "
- If the node's
[systemId](#dfn-systemid)
is not the empty string then append the following, in the order listed, to markup:- "
- "
"
" (U+0022 QUOTATION MARK); - The value of the node's
[systemId](#dfn-systemid)
attribute; - "
"
" (U+0022 QUOTATION MARK).
- "
- Append "
>
" (U+003E GREATER-THAN SIGN) to markup. - Return the value of markup.
The algorithm for producing an XML serialization of a DOM node of typeProcessingInstruction is as follows:
- If the require well-formed flag is set (its value is
true
), andnode's[target](#dfn-target)
contains a ":
" (U+003A COLON) character or is an ASCII case-insensitive match for the string "xml
", thenthrow an exception; the serialization of this node's[target](#dfn-target)
would not be well-formed. - If the require well-formed flag is set (its value is
true
), andnode's[data](#dfn-data)
contains characters that are not matched by the XMLChar production or contains the string "?>
" (U+003F QUESTION MARK, U+003E GREATER-THAN SIGN), then throw an exception; the serialization of thisnode's[data](#dfn-data)
would not be well-formed. - Let markup be the concatenation of the following, in the order listed:
- "
<?
" (U+003C LESS-THAN SIGN, U+003F QUESTION MARK); - The value of node's
[target](#dfn-target)
; - "
- The value of node's
[data](#dfn-data)
; - "
?>
" (U+003F QUESTION MARK, U+003E GREATER-THAN SIGN).
- "
- Return the value of markup.
The HTML specification [HTML5] defines the following terms used in this document:
- The general concepts: an active document;
- Parsing concepts: the fragment parsing algorithm;HTML parser;parsing XHTML documents;XML parser;
- A document location
- The following elements:meta,noscript,script andtemplate
- void elements
- The template's template contents
- The [CEReactions] IDL extended attribute
- The innerHTML property;
- The outerHTML property;
- The insertAdjacentHTML method; The DOM specification [DOM4] defines the following terms used in this document:
- The following concepts:case-sensitive andASCII case-insensitive string comparisons; a node's children,first child,next sibling andparent; the content type andencoding; a HTML document; a local name; a namespace concept; a node document; the append,insert andreplace operations;tree order; a range's start node; document URL; a XML document;
- The Attr interface and itsattr.localName,attr.namespaceURI,attr.prefix andattr.value attributes
- The CharacterData interface's data attribute
- The interface
- The Document interface and itsdoctype anddocumentElement attribute
- The DocumentType interface and itsdoctype.name,publicId andsystemId attributes
- The DocumentFragment interface
- The Element interface and itsattributes list,element.localName,element.namespaceURI andelement.prefix attributes,setAttribute method
- The Node interface
- The ProcessingInstruction interface and itstarget attribute
- The Range interface
- The Text interface
- The following DOMExceptions: "InvalidStateError", "NoModificationAllowedError" and "SyntaxError",
- XMLDocument The following terms used in this document are defined by [DOM]:
- The ShadowRoot interface The following terms used in this document are defined by [XML10]:
- The AttValue,Char,EmptyElemTag,Name andPubidChar productions
- empty-element tag The ECMAScript [ECMA-262] (commonly "JavaScript") specification defines these terms:
- The TypeError exception The Web IDL [WebIDL] specification defines:
- The [LegacyNullToEmptyString] IDL extended attribute
The following is an informative summary of the changes since the last publication of this specification. A complete revision history of the Editor's Drafts of this specification can be found at theW3C Github Repository and older revisions at theW3C Mercurial server.
- 2016-06 WD - Editorial restructuring of the document; monolithic XML serialization algorithm factored into sections. Dependencies clarified. XML Serialization algorithm updated to get closer to interoperable browser behavior.
- Incorporated non-normative changes from previous Last Call document.
We acknowledge with gratitude the original work of Ms2ger and others at the WHATWG, who created and maintained the original DOM Parsing and Serialization Living Standard upon which this specification is based.
Thanks to C. Scott Ananian, Victor Costan, Aryeh Gregor, Anne van Kesteren, Arkadiusz Michalski, Simon Pieters, Henri Sivonen, Josh Soref and Boris Zbarsky, for their useful comments.
Special thanks to Ian Hickson for first defining the innerHTML and outerHTML attributes, and the insertAdjacentHTML method in [HTML5] and his useful comments.
[DOM4]
DOM Standard. Anne van Kesteren. WHATWG. Living Standard. URL: https://dom.spec.whatwg.org/
[ECMA-262]
ECMAScript Language Specification. Ecma International. URL: https://tc39.es/ecma262/multipage/
[HTML5]
HTML5. Ian Hickson; Robin Berjon; Steve Faulkner; Travis Leithead; Erika Doyle Navara; Theresa O'Connor; Silvia Pfeiffer. W3C. 27 March 2018. W3C Recommendation. URL: https://www.w3.org/TR/html5/
[WEBIDL]
Web IDL Standard. Edgar Chen; Timothy Gu. WHATWG. Living Standard. URL: https://webidl.spec.whatwg.org/
[XML10]
Extensible Markup Language (XML) 1.0 (Fifth Edition). Tim Bray; Jean Paoli; Michael Sperberg-McQueen; Eve Maler; François Yergeau et al. W3C. 26 November 2008. W3C Recommendation. URL: https://www.w3.org/TR/xml/