xast-util-to-xml

4.0.0 · active · verified Sun Apr 19

xast-util-to-xml is a utility within the unified (syntax-tree) ecosystem designed to serialize an xast (XML Abstract Syntax Tree) into a string of XML. The current stable version is 4.0.0, which requires Node.js 16 or higher and is ESM-only. Releases tend to follow a feature-driven cadence, with new major versions introducing breaking changes, particularly around module systems and Node.js compatibility. Key differentiators include its adherence to the unist/xast specification, robust TypeScript type support, and granular options for controlling XML serialization, such as closing empty elements (`<foo/>` vs `<foo></foo>`), preferred attribute quotes, and handling of raw nodes. It is commonly used when converting parsed XML back into a string, either for final output or integration with other tools, offering fine-tuned control over the output format for tasks like minification or pretty-printing.

Common errors

Warnings

Install

Imports

Quickstart

This example demonstrates how to create an xast tree using `unist-builder` and `xastscript`, and then serialize it to an XML string using `toXml`, applying custom options.

import { u } from 'unist-builder'
import { x } from 'xastscript'
import { toXml } from 'xast-util-to-xml'

const tree = u('root', [
  u('instruction', {name: 'xml'}, 'version="1.0" encoding="utf-8"'),
  u('text', '\n'),
  x('ncx', {xmlns: 'http://www.daisy.org/z3986/2005/ncx/', version: '2005-1'}, [
    u('text', '\n  '),
    x('head', [
      u('text', '\n    '),
      x('meta', {name: 'dtb:uid', content: 'urn:isbn:9781234567891'}),
      u('text', '\n  ')
    ]),
    u('text', '\n  '),
    x('docTitle', [x('text', 'A Christmas Carol')]),
    u('text', '\n  '),
    x('docAuthor', [x('text', 'Charles Dickens')]),
    u('text', '\n')
  ])
])

const xmlOutput = toXml(tree, { closeEmptyElements: true, quote: "'" })
console.log(xmlOutput)
// Expected output:
// <?xml version='1.0' encoding='utf-8'?>
// <ncx xmlns='http://www.daisy.org/z3986/2005/ncx/' version='2005-1'>
//   <head>
//     <meta name='dtb:uid' content='urn:isbn:9781234567891'/>
//   </head>
//   <docTitle><text>A Christmas Carol</text></docTitle>
//   <docAuthor><text>Charles Dickens</text></docAuthor>
// </ncx>

view raw JSON →