unified

Project: syntax-tree/hast-util-to-xast

Package: hast-util-to-xast@2.0.0

  1. Dependents: 3
  2. hast utility to transform to xast
  1. util 137
  2. utility 133
  3. unist 120
  4. html 112
  5. hast 61
  6. hast-util 40
  7. xast 8
  8. xml 8
  9. xast-util 7
  10. dsl 5

hast-util-to-xast

Build Coverage Downloads Size Sponsors Backers Chat

hast (HTML / SVG) utility to transform trees to xast (XML).

Install

This package is ESM only: Node 12+ is needed to use it and it must be imported instead of required.

npm:

npm install hast-util-to-xast

Use

Say we have an example.html file, that looks as follows:

<!doctypehtml>
<title>Hello, World!</title>
<h1>πŸ‘‹, 🌍</h1>

…and our script, example.js, looks as follows:

import fs from 'node:fs'
import {unified} from 'unified'
import rehypeParse from 'rehype-parse'
import {toXast} from 'hast-util-to-xast'
import {toXml} from 'xast-util-to-xml'

// Get the HTML syntax tree:
const hast = unified()
  .use(rehypeParse)
  .parse(fs.readFileSync('example.html'))

// Turn hast to xast:
const xast = toXast(hast)

// Serialize xast:
console.log(toXml(xast))

Yields:

<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head><title>Hello, World!</title>
</head><body><h1>πŸ‘‹, 🌍</h1>
</body></html>

API

This package exports the following identifiers: toXast. There is no default export.

toXast(node[, space|options])

Transform the given hast tree to xast.

space

Treated as options.space.

options
options.space

Whether the root of the tree is in the 'html' or 'svg' space (enum, 'svg' or 'html', default: 'html').

If an svg element is found in the HTML space, toXast automatically switches to the SVG space when entering the element, and switches back when exiting.

You can also switch explicitly with xmlns properties in hast, but note that only HTML and SVG are supported.

Security

Both HTML and XML can be a dangerous language: don’t trust user-provided data. Use hast-util-santize to make the hast tree safe before using this utility.

Contribute

See contributing.md in syntax-tree/.github for ways to get started. See support.md for ways to get help.

This project has a code of conduct. By interacting with this repository, organization, or community you agree to abide by its terms.

License

MIT Β© Titus Wormer