Attach namespace information to a xast XML element tree.
This library exposes a function which takes a xast tree and attaches namespace information to each element.
npm install xast-namespacesimport assert from 'node:assert/strict'
import { attachNamespaces } from 'xast-namespaces'
const tree = {
type: 'element',
name: 'ns:parent',
attributes: {
'xmlns:ns': 'https://ns.example'
},
children: [
{
type: 'element',
name: 'ns:child',
attributes: {
'ns:attr': 'value'
},
children: []
}
]
}
const result = attachNamespaces(tree)
assert.deepStrictEqual(result, {
type: 'element',
name: 'ns:parent',
namespace: 'ns',
namespaceURI: 'https://ns.example',
localName: 'parent',
namespaces: {
ns: 'https://ns.example'
},
attributes: {
'xmlns:ns': 'https://ns.example'
},
namespacedAttributes: [
{
type: 'attribute',
name: 'xmlns:ns',
namespace: 'xmlns',
namespaceURI: undefined,
localName: 'ns',
value: 'https://ns.example'
}
],
children: [
{
type: 'element',
name: 'ns:child',
namespace: 'ns',
namespaceURI: 'https://ns.example',
localName: 'child',
namespaces: {
ns: 'https://ns.example'
},
attributes: {
'ns:attr': 'value'
},
namespacedAttributes: [
{
type: 'attribute',
name: 'ns:attr',
namespace: 'ns',
namespaceURI: 'https://ns.example',
localName: 'attr',
value: 'value'
}
],
children: []
}
]
})Attach XML namespace data to a xast tree.
treeThe document tree to attach namespace data to. If axastroot is passed, its element child will be used.
A copy of the tree, but with namespace data attached.
This project is compatible with Node.js 22 or greater.