| [9af201e] | 1 | # w3c-xmlserializer
|
|---|
| 2 |
|
|---|
| 3 | An XML serializer that follows the [W3C specification](https://w3c.github.io/DOM-Parsing/).
|
|---|
| 4 |
|
|---|
| 5 | This package can be used in Node.js, as long as you feed it a DOM node, e.g. one produced by [jsdom](https://github.com/jsdom/jsdom).
|
|---|
| 6 |
|
|---|
| 7 | ## Basic usage
|
|---|
| 8 |
|
|---|
| 9 | Assume you have a DOM tree rooted at a node `node`. In Node.js, you could create this using [jsdom](https://github.com/jsdom/jsdom) as follows:
|
|---|
| 10 |
|
|---|
| 11 | ```js
|
|---|
| 12 | const { JSDOM } = require("jsdom");
|
|---|
| 13 |
|
|---|
| 14 | const { document } = new JSDOM().window;
|
|---|
| 15 | const node = document.createElement("akomaNtoso");
|
|---|
| 16 | ```
|
|---|
| 17 |
|
|---|
| 18 | Then, you use this package as follows:
|
|---|
| 19 |
|
|---|
| 20 |
|
|---|
| 21 | ```js
|
|---|
| 22 | const serialize = require("w3c-xmlserializer");
|
|---|
| 23 |
|
|---|
| 24 | console.log(serialize(node));
|
|---|
| 25 | // => '<akomantoso xmlns="http://www.w3.org/1999/xhtml"></akomantoso>'
|
|---|
| 26 | ```
|
|---|
| 27 |
|
|---|
| 28 | ## `requireWellFormed` option
|
|---|
| 29 |
|
|---|
| 30 | By default the input DOM tree is not required to be "well-formed"; any given input will serialize to some output string. You can instead require well-formedness via
|
|---|
| 31 |
|
|---|
| 32 | ```js
|
|---|
| 33 | serialize(node, { requireWellFormed: true });
|
|---|
| 34 | ```
|
|---|
| 35 |
|
|---|
| 36 | which will cause `Error`s to be thrown when non-well-formed constructs are encountered. [Per the spec](https://w3c.github.io/DOM-Parsing/#dfn-require-well-formed), this largely is about imposing constraints on the names of elements, attributes, etc.
|
|---|
| 37 |
|
|---|
| 38 | As a point of reference, on the web platform:
|
|---|
| 39 |
|
|---|
| 40 | * The [`innerHTML` getter](https://w3c.github.io/DOM-Parsing/#dom-innerhtml-innerhtml) uses the require-well-formed mode, i.e. trying to get the `innerHTML` of non-well-formed subtrees will throw.
|
|---|
| 41 | * The [`xhr.send()` method](https://xhr.spec.whatwg.org/#the-send()-method) does not require well-formedness, i.e. sending non-well-formed `Document`s will serialize and send them anyway.
|
|---|