Movatterモバイル変換


[0]ホーム

URL:


W3C

DOM Parsing and Serialization

DOMParser, XMLSerializer, innerHTML, and similar APIs

W3C Editor's Draft

More details about this document
This version:
https://w3c.github.io/DOM-Parsing/
Latest published version:
https://www.w3.org/TR/DOM-Parsing/
Latest editor's draft:
https://w3c.github.io/DOM-Parsing/
History:
https://www.w3.org/standards/history/DOM-Parsing/
Editor:
Travis Leithead (Microsoft)
Feedback:
www-dom@w3.org with subject lineDOM-Parsing (archives)
Test Suites
http://w3c-test.org/domparsing/
http://w3c-test.org/html/syntax/
Participate
We are on Github.
Bugzilla Bug list.
Github Issues.
Commit history.
Mailing list.

Copyright © 2025World Wide Web Consortium.W3C®liability,trademark andpermissive document license rules apply.


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 currentW3C publications and the latest revision of this technical report can be found in theW3C technical reports index at https://www.w3.org/TR/.

This document was published by theWeb Applications Working Group as an Editor's Draft.

Publication as an Editor's Draft does not imply endorsement byW3C 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 theW3C Patent Policy.

This document is governed by the03 November 2023W3C Process Document.

Candidate Recommendation Exit Criteria

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 acase-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.

Extensibility

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.

1.Introduction

A document object model (DOM) is an in-memory representation of various types ofNodes where eachNode is connected in a tree. The [HTML5] and [DOM4] specifications describe DOM and itsNodes is greater detail.

Parsing is the term used for converting a string representation of a DOM into an actual DOM, andSerializing 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: theinnerHTML API is a common way to both parse and serialize a DOM (it does both). If a particularNode, has the following in-memory DOM:
HTMLDivElement (nodeName:"div")┃┣━ HTMLSpanElement (nodeName:"span")┃  ┃┃  ┗━ Text (data:"some ")┃┗━ HTMLElement (nodeName:"em")   ┃   ┗━ Text (data:"text!")
And theHTMLDivElement node is stored in a variablemyDiv, then to serializemyDiv's children simplyget (read) theElement'sinnerHTML property (this triggers the serialization):
var serializedChildren = myDiv.innerHTML;// serializedChildren has the value:// "<span>some </span><em>text!</em>"

To parse new children formyDiv from a string (replacing its existing children), simplyset theinnerHTML property (this triggers parsing of the assigned string):

myDiv.innerHTML ="<span>new</span><em>children!</em>";

This specification describes two flavors ofparsing andserializing: 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 theNode in the DOM.Round-tripping is especially tricky for an XML serialization, which must be concerned with preserving theNode'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 theHTMLScriptElementNode'snamespace in order to preserve the identity of thescript element, and to allow the serialized string toround-trip through an XML parser. Assuming thatroot is in a variable namedroot:
var xmlSerialization =newXMLSerializer().serializeToString(root);// xmlSerialization has the value:// "<root><script xmlns="http://www.w3.org/1999/xhtml">alert('hello world')</script></root>"

The termcontext 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):

2.APIs for parsing and serializing DOM

2.1TheDOMParser interface

The definition ofDOMParser has moved tothe HTML Standard.

2.2TheXMLSerializer interface

The definition ofXMLSerializer has moved tothe HTML Standard.

2.3TheInnerHTML mixin

The definition ofInnerHTML has moved tothe HTML Standard.

2.4Extensions to theElement interface

The definition ofouterHTML has moved tothe HTML Standard.

The definition ofinsertAdjacentHTML has moved tothe HTML Standard.

2.5Extensions to theRange interface

The definition ofcreateContextualFragment has moved tothe HTML Standard.

3.Algorithms for parsing and serializing

3.1Parsing

The definition offragment parsing algorithm has moved tothe HTML Standard.

3.2Serializing

The definition offragment serializing algorithm has moved tothe HTML Standard.

3.2.1XML Serialization

AnXML serialization differs from an HTML serialization in the following ways:

  • Elements andattributes will always be serialized such that theirnamespaceURI 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 theHTML namespace containing nochildren, are serialized using theempty-element tag syntax (i.e., according to the XMLEmptyElemTag production).

Otherwise, the algorithm for producing anXML serialization is designed to produce a serialization that is compatible with theHTML parser. For example, elements in theHTML namespace that contain nochild nodes are serialized with an explicit begin and end tag rather than using theempty-element tag syntax.

Note

Per [DOM4],Attr objects do not inherit fromNode, and thus cannot be serialized by theXML serialization algorithm. An attempt to serialize anAttr object will result in an empty string.

To produce anXML serialization of aNodenode given a flagrequire well-formed, run the following steps:

  1. Letnamespace be acontext namespace with valuenull. Thecontext namespace tracks theXML serialization algorithm's current default namespace. Thecontext namespace is changed when either anElementNode has a default namespace declaration, or the algorithm generates a default namespace declaration for theElementNode to match its own namespace. The algorithm assumes no namespace (null) to start.
  2. Letprefix map be a newnamespace prefix map.
  3. Add theXML namespace with prefix value "xml" toprefix map.
  4. Letprefix index be agenerated namespace prefix index with value1. Thegenerated 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 thegenerate a prefix algorithm.
  5. Return the result of running theXML serialization algorithm onnode passing thecontext namespacenamespace,namespace prefix mapprefix map,generated namespace prefix index reference toprefix index, and the flagrequire well-formed. If anexception occurs during the execution of the algorithm, then catch that exception and throw an "InvalidStateError"DOMException.

Each of the following algorithms forproducing an XML serialization of a DOM node take as input anode to serialize and the following arguments:

TheXML serialization algorithmproduces an XML serialization of an arbitrary DOM nodenode based on thenode'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. Ifnode's interface is:

Element
Run the algorithm forXML serializing an Element nodenode.
Document
Run the algorithm forXML serializing a Document nodenode.
Comment
Run the algorithm forXML serializing a Comment nodenode.
Text
Run the algorithm forXML serializing a Text nodenode.
DocumentFragment
Run the algorithm forXML serializing a DocumentFragment nodenode.
DocumentType
Run the algorithm forXML serializing a DocumentType nodenode.
ProcessingInstruction
Run the algorithm forXML serializing a ProcessingInstruction nodenode.
AnAttr object
Return an empty string.
Anything else
Throw aTypeError. OnlyNodes andAttr objects can be serialized by this algorithm.
Each of the above referenced algorithms are detailed in the sections that follow.
3.2.1.1XML serializing an Element node
The algorithm forproducing an XML serialization of a DOM node of typeElement is as follows:
  1. If therequire well-formed flag is set (its value istrue), and thisnode'slocalName attribute contains the character ":" (U+003A COLON) or does not match the XMLName production, thenthrow an exception; the serialization of thisnode would not be a well-formed element.
  2. Letmarkup be the string "<" (U+003C LESS-THAN SIGN).
  3. Letqualified name be an empty string.
  4. Letskip end tag be a boolean flag with valuefalse.
  5. Letignore namespace definition attribute be a boolean flag with valuefalse.
  6. Givenprefix map,copy a namespace prefix map and letmap be the result.
  7. Letlocal prefixes map be an empty map. The map has uniqueNodeprefix strings as its keys, with correspondingnamespaceURINode 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 currentElement) and one that is not.

  8. Letlocal default namespace be the result ofrecording the namespace information fornode givenmap andlocal prefixes map.
    Note

    The above step will updatemap with any found namespace prefix definitions, add the found prefix definitions to thelocal prefixes map and return alocal default namespace value defined by a default namespace attribute if one exists. Otherwise it returnsnull.

  9. Letinherited ns be a copy ofnamespace.
  10. Letns be the value ofnode'snamespaceURI attribute.
  11. Ifinherited ns is equal tons, then:
    1. Iflocal default namespace is notnull, then setignore namespace definition attribute totrue.
    2. Ifns is theXML namespace, then append toqualified name the concatenation of the string "xml:" and the value ofnode'slocalName.
    3. Otherwise, append toqualified name the value ofnode'slocalName.Thenode'sprefix if it exists, is dropped.
    4. Append the value ofqualified name tomarkup.
  12. Otherwise,inherited ns is not equal tons (thenode's own namespace is different from the context namespace of its parent). Run these sub-steps:
    1. Letprefix be the value ofnode'sprefix attribute.
    2. Letcandidate prefix be the result ofretrieving a preferred prefix stringprefix frommap given namespacens.
      Note

      The above may returnnull if no namespace keyns exists inmap.

    3. If the value ofprefix matches "xmlns", then run the following steps:
      1. If therequire well-formed flag is set, then throw an error. AnElement withprefix "xmlns" will not legally round-trip in a conformingXML parser.
      2. Letcandidate prefix be the value ofprefix.
    4. Found a suitable namespace prefix: ifcandidate prefix is notnull (a namespace prefix is defined which maps tons), then:
      Note

      The following may serialize a differentprefix than theElement's existingprefix if it already had one. However, theretrieving a preferred prefix string algorithm already tried to match the existing prefix if possible.

      1. Append toqualified name the concatenation ofcandidate prefix, ":" (U+003A COLON), andnode'slocalName.There exists on thisnode or thenode's ancestry a namespace prefix definition that defines thenode's namespace.
      2. If thelocal default namespace is notnull (there exists a locally-defined default namespace declaration attribute) and its value is not theXML namespace, then letinherited ns get the value oflocal default namespace unless thelocal default namespace is the empty string in which case let it getnull (thecontext namespace is changed to the declared default, rather than thisnode's own namespace).
        Note

        Any default namespace definitions or namespace prefixes that define theXML namespace are omitted when serializing this node's attributes.

      3. Append the value ofqualified name tomarkup.
    5. Otherwise, ifprefix is notnull, then:
      Note

      By this step, there is no namespace or prefix mapping declaration in thisnode (or any parentnode visited by this algorithm) that definesprefix otherwise the step labelledFound a suitable namespace prefix would have been followed. The sub-steps that follow will create a new namespace prefix declaration forprefix and ensure thatprefix does not conflict with an existing namespace prefix declaration of the samelocalName innode'sattribute list.

      1. If thelocal prefixes map contains a key matchingprefix, then letprefix be the result ofgenerating a prefix providing as inputmap,ns, andprefix index.
      2. Addprefix tomap given namespacens.
      3. Append toqualified name the concatenation ofprefix, ":" (U+003A COLON), andnode'slocalName.
      4. Append the value ofqualified name tomarkup.
      5. Append the following tomarkup, in the order listed:
        Note

        The following serializes a namespace prefix declaration forprefix which was just added to themap.

        1. "" (U+0020 SPACE);
        2. The string "xmlns:";
        3. The value ofprefix;
        4. "="" (U+003D EQUALS SIGN, U+0022 QUOTATION MARK);
        5. The result ofserializing an attribute value givenns and therequire well-formed flag as input;
        6. """ (U+0022 QUOTATION MARK).
        7. Iflocal default namespace is notnull (there exists a locally-defined default namespace declaration attribute), then letinherited ns get the value oflocal default namespace unless thelocal default namespace is the empty string in which case let it getnull.
    6. Otherwise, iflocal default namespace isnull, orlocal default namespace is notnull and its value is not equal tons, then:
      Note

      At this point, the namespace for this node still needs to be serialized, but there's noprefix (orcandidate prefix) availble; the following uses the default namespace declaration to define the namespace--optionally replacing an existing default declaration if present.

      1. Set theignore namespace definition attribute flag totrue.
      2. Append toqualified name the value ofnode'slocalName.
      3. Let the value ofinherited ns bens.
        Note

        The new default namespace will be used in the serialization to define thisnode's namespace and act as thecontext namespace for itschildren.

      4. Append the value ofqualified name tomarkup.
      5. Append the following tomarkup, in the order listed:
        Note

        The following serializes the new (or replacement) default namespace definition.

        1. "" (U+0020 SPACE);
        2. The string "xmlns";
        3. "="" (U+003D EQUALS SIGN, U+0022 QUOTATION MARK);
        4. The result ofserializing an attribute value givenns and therequire well-formed flag as input;
        5. """ (U+0022 QUOTATION MARK).
    7. Otherwise, thenode has alocal default namespace that matchesns. Append toqualified name the value ofnode'slocalName, let the value ofinherited ns bens, and append the value ofqualified name tomarkup.
      Note

      All of the combinations wherens is not equal toinherited ns are handled above such thatnode will be serialized preserving its originalnamespaceURI.

  13. Append tomarkup the result of theXML serialization ofnode's attributes givenmap,prefix index,local prefixes map,ignore namespace definition attribute flag, andrequire well-formed flag.
  14. Ifns is theHTML namespace, and thenode's list ofchildren is empty, and thenode'slocalName matches any one of the followingvoid elements: "area", "base", "basefont", "bgsound", "br", "col", "embed", "frame", "hr", "img", "input", "keygen", "link", "menuitem", "meta", "param", "source", "track", "wbr"; then append the following tomarkup, in the order listed:
    1. "" (U+0020 SPACE);
    2. "/" (U+002F SOLIDUS).
    and set theskip end tag flag totrue.
  15. Ifns is not theHTML namespace, and thenode's list ofchildren is empty, then append "/" (U+002F SOLIDUS) tomarkup and set theskip end tag flag totrue.
  16. Append ">" (U+003E GREATER-THAN SIGN) tomarkup.
  17. If the value ofskip end tag istrue, then return the value ofmarkup and skip the remaining steps. Thenode is a leaf-node.
  18. Ifns is theHTML namespace, and thenode'slocalName matches the string "template", then this is atemplate element. Append tomarkup the result ofXML serializing a DocumentFragment node given thetemplate element'stemplate contents (aDocumentFragment), providinginherited ns,map,prefix index, and therequire well-formed flag.
    Note

    This allowstemplate content to round-trip , given the rules forparsing XHTML documents.

  19. Otherwise, append tomarkup the result of running theXML serialization algorithm on each ofnode'schildren, intree order, providinginherited ns,map,prefix index, and therequire well-formed flag.
  20. Append the following tomarkup, in the order listed:
    1. "</" (U+003C LESS-THAN SIGN, U+002F SOLIDUS);
    2. The value ofqualified name;
    3. ">" (U+003E GREATER-THAN SIGN).
  21. Return the value ofmarkup.
3.2.1.1.1Recording the namespace

This following algorithm will update thenamespace prefix map with any found namespace prefix definitions, add the found prefix definitions to thelocal prefixes map, and return alocal default namespace value defined by a default namespace attribute if one exists. Otherwise it returnsnull.

Whenrecording the namespace information for anElementelement, given anamespace prefix mapmap and alocal prefixes map (initially empty), the user agent must run the following steps:

  1. Letdefault namespace attr value benull.
  2. Main: For eachattributeattr inelement'sattributes, in the order they are specified in theelement'sattribute list:
    Note

    The following conditional steps find namespace prefixes. Only attributes in theXMLNS namespace are considered (e.g., attributes made to look like namespace declarations viasetAttribute("xmlns:pretend-prefix","pretend-namespace") are not included).

    1. Letattribute namespace be the value ofattr'snamespaceURI value.
    2. Letattribute prefix be the value ofattr'sprefix.
    3. If theattribute namespace is theXMLNS namespace, then:
      1. Ifattribute prefix isnull, thenattr is a default namespace declaration. Set thedefault namespace attr value toattr'svalue and stop running these steps, returning toMain to visit the next attribute.
      2. Otherwise, theattribute prefix is notnull andattr is a namespace prefix definition. Run the following steps:
        1. Letprefix definition be the value ofattr'slocalName.
        2. Letnamespace definition be the value ofattr'svalue.
        3. Ifnamespace definition is theXML namespace, then stop running these steps, and return toMain 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. Ifnamespace definition is the empty string (the declarative form of having no namespace), then letnamespace definition benull instead.
        5. Ifprefix definition isfound inmap given the namespacenamespace definition, then stop running these steps, and return toMain to visit the next attribute.
          Note

          This step avoids adding duplicate prefix definitions for the same namespace in themap. This has the side-effect of avoiding later serialization of duplicate namespace prefix declarations in any descendant nodes.

        6. Add the prefixprefix definition tomap given namespacenamespace definition.
        7. Add the value ofprefix definition as a new key to thelocal prefixes map, with thenamespace definition as the key's value replacing the value ofnull with the empty string if applicable.
  3. Return the value ofdefault namespace attr value.
    Note

    The empty string is a legitimate return value and is not converted tonull.

3.2.1.1.2The Namespace Prefix Map

Anamespace prefix map is a map that associatesnamespaceURI andnamespace prefix lists, wherenamespaceURI values are the map's unique keys (which can include thenull value representing no namespace), and ordered lists of associatedprefix 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 seenprefix for a givennamespaceURI is at the end of its respectivelist. The list is searched to find potentially matching prefixes, and if no matches are found for the givennamespaceURI, then the lastprefix in the list is used. Seecopy a namespace prefix map andretrieve a preferred prefix string for additional details.

Tocopy a namespace prefix mapmap means to copy themap's keys into a new emptynamespace 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.

Toretrieve a preferred prefix stringpreferred prefix from thenamespace prefix mapmap given a namespacens, the user agent should:

  1. Letcandidates list be the result of retrieving alist frommap where there exists a key inmap that matches the value ofns or if there is no such key, then stop running these steps, and return thenull value.
  2. Otherwise, for each prefix valueprefix incandidates list, iterating from beginning to end:
    Note

    There will always be at least one prefix value in the list.

    1. Ifprefix matchespreferred prefix, then stop running these steps and returnprefix.
    2. Ifprefix is the last item in thecandidates list, then stop running these steps and returnprefix.

To check if a prefix stringprefix isfound in anamespace prefix mapmap given a namespacens, the user agent should:

  1. Letcandidates list be the result of retrieving alist frommap where there exists a key inmap that matches the value ofns or if there is no such key, then stop running these steps, and returnfalse.
  2. If the value ofprefix occurs at least once incandidates list, returntrue, otherwise returnfalse.

Toadd a prefix stringprefix to thenamespace prefix mapmap given a namespacens, the user agent should:

  1. Letcandidates list be the result of retrieving alist frommap where there exists a key inmap that matches the value ofns or if there is no such key, then letcandidates list benull.
  2. Ifcandidates list isnull, then create a newlist withprefix as the only item in thelist, and associate thatlist with a new keyns inmap.
  3. Otherwise, appendprefix to the end ofcandidates list.
    Note

    The steps inretrieve a preferred prefix string use thelist to track the most recently used (MRU)prefix associated with a given namespace, which will be theprefix at the end of the list. This list may contain duplicates of the sameprefix value seen earlier (and that's OK).

3.2.1.1.3Serializing an Element's attributes

TheXML serialization of the attributes of anElementelement together with anamespace prefix mapmap, agenerated namespace prefix indexprefix index reference, alocal prefixes map, aignore namespace definition attribute flag, and arequire well-formed flag, is the result of the following algorithm:

  1. Letresult be the empty string.
  2. Letlocalname set be a new emptynamespace localname set. Thislocalname set will contain tuples of unique attributenamespaceURI andlocalName pairs, and is populated as eachattr is processed.This set is used to [optionally] enforce the well-formed constraint that an element cannot have two attributes with the samenamespaceURI andlocalName. This can occur when two otherwise identical attributes on the same element differ only by their prefix values.
  3. Loop: For eachattributeattr inelement'sattributes, in the order they are specified in theelement'sattribute list:
    1. If therequire well-formed flag is set (its value istrue), and thelocalname set contains a tuple whose values match those of a new tuple consisting ofattr'snamespaceURI attribute andlocalName attribute, thenthrow an exception; the serialization of thisattr would fail to produce a well-formed element serialization.
    2. Create a new tuple consisting ofattr'snamespaceURI attribute andlocalName attribute, and add it to thelocalname set.
    3. Letattribute namespace be the value ofattr'snamespaceURI value.
    4. Letcandidate prefix benull.
    5. Ifattribute namespace is notnull, then run these sub-steps:
      1. Letcandidate prefix be the result ofretrieving a preferred prefix string frommap given namespaceattribute namespace with preferred prefix beingattr'sprefix value.
      2. If the value ofattribute namespace is theXMLNS namespace, then run these steps:
        1. If any of the following are true, then stop running these steps and gotoLoop to visit the next attribute:
        2. If therequire well-formed flag is set (its value istrue), and the value ofattr'svalue attribute matches theXMLNS namespace, then throw an exception; the serialization of this attribute would produce invalid XML because theXMLNS namespace is reserved and cannot be applied as an element's namespace via XML parsing.
          Note

          DOM APIs do allow creation of elements in theXMLNS namespace but with strict qualifications.

        3. If therequire well-formed flag is set (its value istrue), and the value ofattr'svalue 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. theattr'sprefix matches the string "xmlns", then letcandidate prefix be the string "xmlns".
      3. Otherwise, theattribute namespace in not theXMLNS namespace. Run these steps:
        1. Letcandidate prefix be the result ofgenerating a prefix providingmap,attribute namespace, andprefix index as input.
        2. Append the following toresult, in the order listed:
          1. "" (U+0020 SPACE);
          2. The string "xmlns:";
          3. The value ofcandidate prefix;
          4. "="" (U+003D EQUALS SIGN, U+0022 QUOTATION MARK);
          5. The result ofserializing an attribute value givenattribute namespace and therequire well-formed flag as input;
          6. """ (U+0022 QUOTATION MARK).
    6. Append a "" (U+0020 SPACE) toresult.
    7. Ifcandidate prefix is notnull, then append toresult the concatenation ofcandidate prefix with ":" (U+003A COLON).
    8. If therequire well-formed flag is set (its value istrue), and thisattr'slocalName attribute contains the character ":" (U+003A COLON) or does not match the XMLName production or equals "xmlns" andattribute namespace isnull, thenthrow an exception; the serialization of thisattr would not be a well-formed attribute.
    9. Append the following strings toresult, in the order listed:
      1. The value ofattr'slocalName;
      2. "="" (U+003D EQUALS SIGN, U+0022 QUOTATION MARK);
      3. The result ofserializing an attribute value givenattr'svalue attribute and therequire well-formed flag as input;
      4. """ (U+0022 QUOTATION MARK).
  4. Return the value ofresult.

Whenserializing an attribute value given anattribute value andrequire well-formed flag, the user agent must run the following steps:

  1. If therequire well-formed flag is set (its value istrue), andattribute value contains characters that are not matched by the XMLChar production, thenthrow an exception; the serialization of thisattribute value would fail to produce a well-formed element serialization.
  2. Ifattribute value isnull, then return the empty string.
  3. Otherwise,attribute value is a string. Return the value ofattribute value, first replacing any occurrences of the following:
    1. "&" with "&amp;"
    2. """ with "&quot;"
    3. "<" with "&lt;"
    4. ">" with "&gt;"
    Note

    This matches behavior present in browsers, and goes above and beyond the grammar requirement in the XML specification'sAttValue production by also replacing ">" characters.

3.2.1.1.4Generating namespace prefixes

Togenerate a prefix given anamespace prefix mapmap, a stringnew namespace, and a reference to agenerated namespace prefix indexprefix index, the user agent must run the following steps:

  1. Letgenerated prefix be the concatenation of the string "ns" and the current numerical value ofprefix index.
  2. Let the value ofprefix index be incremented by one.
  3. Add tomap thegenerated prefix given thenew namespace namespace.
  4. Return the value ofgenerated prefix.
3.2.1.2XML serializing a Document node
The algorithm forproducing an XML serialization of a DOM node of typeDocument is as follows:

If therequire well-formed flag is set (its value istrue), and thisnode has nodocumentElement (thedocumentElement attribute's value isnull), thenthrow an exception; the serialization of thisnode would not be a well-formed document.

Otherwise, run the following steps:

  1. Letserialized document be an empty string.
  2. For eachchildchild ofnode, intree order, run theXML serialization algorithm on thechild passing along the provided arguments, and append the result toserialized document.
    Note

    This will serialize any number ofProcessingInstruction andComment nodes both before and after theDocument'sdocumentElement node, including at most oneDocumentType node. (Text nodes are not allowed as children of theDocument.)

  3. Return the value ofserialized document.
3.2.1.3XML serializing a Comment node
The algorithm forproducing an XML serialization of a DOM node of typeComment is as follows:

If therequire well-formed flag is set (its value istrue), andnode'sdata contains characters that are not matched by the XMLChar production or contains "--" (two adjacent U+002D HYPHEN-MINUS characters) or that ends with a "-" (U+002D HYPHEN-MINUS) character, thenthrow an exception; the serialization of thisnode'sdata would not be well-formed.

Otherwise, return the concatenation of "<!--",node'sdata, and "-->".

3.2.1.4XML serializing a Text node
The algorithm forproducing an XML serialization of a DOM node of typeText is as follows:
  1. If therequire well-formed flag is set (its value istrue), andnode'sdata contains characters that are not matched by the XMLChar production, thenthrow an exception; the serialization of thisnode'sdata would not be well-formed.
  2. Letmarkup be the value ofnode'sdata.
  3. Replace any occurrences of "&" inmarkup by "&amp;".
  4. Replace any occurrences of "<" inmarkup by "&lt;".
  5. Replace any occurrences of ">" inmarkup by "&gt;".
  6. Return the value ofmarkup.
3.2.1.5XML serializing a DocumentFragment node
The algorithm forproducing an XML serialization of a DOM node of typeDocumentFragment is as follows:
  1. Letmarkup the empty string.
  2. For eachchildchild ofnode, intree order, run theXML serialization algorithm on thechild givennamespace,prefix map, a reference toprefix index, and flagrequire well-formed. Concatenate the result tomarkup.
  3. Return the value ofmarkup.
3.2.1.6XML serializing a DocumentType node
The algorithm forproducing an XML serialization of a DOM node of typeDocumentType is as follows:
  1. If therequire well-formed flag istrue and thenode'spublicId attribute contains characters that are not matched by the XMLPubidChar production, thenthrow an exception; the serialization of thisnode would not be a well-formed document type declaration.
  2. If therequire well-formed flag istrue and thenode'ssystemId 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), thenthrow an exception; the serialization of thisnode would not be a well-formed document type declaration.
  3. Letmarkup be an empty string.
  4. Append the string "<!DOCTYPE" tomarkup.
  5. Append "" (U+0020 SPACE) tomarkup.
  6. Append the value of thenode'sname attribute tomarkup. For anode belonging to anHTML document, the value will be all lowercase.
  7. If thenode'spublicId is not the empty string then append the following, in the order listed, tomarkup:
    1. "" (U+0020 SPACE);
    2. The string "PUBLIC";
    3. "" (U+0020 SPACE);
    4. """ (U+0022 QUOTATION MARK);
    5. The value of thenode'spublicId attribute;
    6. """ (U+0022 QUOTATION MARK).
  8. If thenode'ssystemId is not the empty string and thenode'spublicId is set to the empty string, then append the following, in the order listed, tomarkup:
    1. "" (U+0020 SPACE);
    2. The string "SYSTEM".
  9. If thenode'ssystemId is not the empty string then append the following, in the order listed, tomarkup:
    1. "" (U+0020 SPACE);
    2. """ (U+0022 QUOTATION MARK);
    3. The value of thenode'ssystemId attribute;
    4. """ (U+0022 QUOTATION MARK).
  10. Append ">" (U+003E GREATER-THAN SIGN) tomarkup.
  11. Return the value ofmarkup.
3.2.1.7XML serializing a ProcessingInstruction node
The algorithm forproducing an XML serialization of a DOM node of typeProcessingInstruction is as follows:
  1. If therequire well-formed flag is set (its value istrue), andnode'starget contains a ":" (U+003A COLON) character or is anASCII case-insensitive match for the string "xml", thenthrow an exception; the serialization of thisnode'starget would not be well-formed.
  2. If therequire well-formed flag is set (its value istrue), andnode'sdata contains characters that are not matched by the XMLChar production or contains the string "?>" (U+003F QUESTION MARK, U+003E GREATER-THAN SIGN), thenthrow an exception; the serialization of thisnode'sdata would not be well-formed.
  3. Letmarkup be the concatenation of the following, in the order listed:
    1. "<?" (U+003C LESS-THAN SIGN, U+003F QUESTION MARK);
    2. The value ofnode'starget;
    3. "" (U+0020 SPACE);
    4. The value ofnode'sdata;
    5. "?>" (U+003F QUESTION MARK, U+003E GREATER-THAN SIGN).
  4. Return the value ofmarkup.

A.Dependencies

The HTML specification [HTML5] defines the following terms used in this document: The DOM specification [DOM4] defines the following terms used in this document: The following terms used in this document are defined by [DOM]: The following terms used in this document are defined by [XML10]: The ECMAScript [ECMA-262] (commonly "JavaScript") specification defines these terms: The Web IDL [WebIDL] specification defines:

B.Revision History

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.

C.Acknowledgements

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 theinnerHTML andouterHTML attributes, and theinsertAdjacentHTML method in [HTML5] and his useful comments.

D.References

D.1Normative references

[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/


[8]ページ先頭

©2009-2025 Movatter.jp