Following functions can be used to convert an XML document into a string or an object. See serialization settings page for the settings object used by these functions.
Note:
end
function converts the entire XML document, where toString
and toObject
functions convert only the node they are called with.
end
Converts the entire XML document into its string or object representation. end
can be called from anywhere in the document.
end(options
?: object)
options
?: object)options
- serialization options (optional)
const { create } = require('xmlbuilder2');
const doc = create()
.ele('root', { 'att', 'val' })
.ele('foo')
.ele('bar').txt('foobar')
.up()
.ele('baz')
.doc();
console.log(doc.end({ prettyPrint: true }));
<?xml version="1.0"?>
<root att="val">
<foo>
<bar>foobar</bar>
</foo>
<baz/>
</root>
toObject
Converts the node into its object representation.
toObject(options
?: object)
options
?: object)options
- serialization options (optional)
const { create } = require('xmlbuilder2');
const doc = create()
.ele('root', { 'att', 'val' })
.ele('foo')
.ele('bar').txt('foobar')
.up()
.ele('baz')
.doc();
const foo = doc.first().first();
console.log(foo.toObject());
{
foo: {
bar: 'foobar'
}
}
toString
Converts the node into its string representation.
toString(options
?: object)
options
?: object)options
- serialization options (optional)
const { create } = require('xmlbuilder2');
const doc = create()
.ele('root', { 'att', 'val' })
.ele('foo')
.ele('bar').txt('foobar')
.up()
.ele('baz')
.doc();
const foo = doc.first().first();
console.log(foo.toString({ prettyPrint: true }));
<foo>
<bar>foobar</bar>
</foo>