### Install xmlbuilder2 using npm
Source: https://oozcitak.github.io/xmlbuilder2/index
This snippet shows the command to install the xmlbuilder2 package using npm, the Node.js package manager. Ensure you have Node.js and npm installed.
```bash
npm install xmlbuilder2
```
--------------------------------
### Query XML with xpath Module
Source: https://oozcitak.github.io/xmlbuilder2/using-with-external-libraries
This example shows how to use the 'xpath' module to query an XML document created with xmlbuilder2. It demonstrates selecting elements by local name and retrieving their data. It also shows how to handle namespaces.
```javascript
const { create } = require('xmlbuilder2');
const { select } = require('xpath');
const doc = create("The Book");
const nodes = select("//title", doc.node);
console.log(nodes[0].localName); // "title"
console.log(nodes[0].firstChild.data); // "The Book"
console.log(nodes[0].toString()); // "
The Book"
```
```javascript
const { create } = require('xmlbuilder2');
const { select } = require('xpath');
const doc = create("Harry Potter")
const node = select("//*[local-name(.)='title' and namespace-uri(.)='myns']", doc.node)
console.log(node[0].namespaceURI); // "myns"
```
--------------------------------
### Wrap Existing DOM Node with Builder (default options)
Source: https://oozcitak.github.io/xmlbuilder2/builder-functions
Wraps an existing DOM node with default options, returning a builder object. This is a simpler way to start building XML from a DOM node when default configurations are sufficient. It requires only the DOM node as an argument.
```javascript
const { builder } = require('xmlbuilder2');
const node = document.createElement('node');
const xml = builder(node)
.ele('child')
.end({ prettyPrint: true });
console.log(xml);
```
--------------------------------
### Create XML Document in Chunks with createCB using Event Listeners (Node.js)
Source: https://oozcitak.github.io/xmlbuilder2/builder-functions-with-callbacks
An alternative method using `createCB` where event listeners for 'data' and 'end' are attached to the builder object. This achieves the same chunked XML serialization as the previous example but utilizes the EventEmitter pattern.
```javascript
const { createCB } = require('xmlbuilder2');
const { createWriteStream } = require('fs');
const filename = 'path/to/output/file';
const outFile = createWriteStream(filename);
const xmlBuilder = createCB({ prettyPrint: true });
xmlBuilder.on('data', (chunk) => outFile.write(chunk));
xmlBuilder.on('end', () => outFile.end());
xmlBuilder.ele('root')
.ele('foo').up()
.ele('bar').att('fizz', 'buzz').up()
.end();
```
--------------------------------
### Initialize XML Document with xmlbuilder2
Source: https://oozcitak.github.io/xmlbuilder2/serialization
This snippet shows how to create an XML document object using the `create` function from the `xmlbuilder2` library. It parses an XML string and stores the document representation in the `doc` variable, serving as the input for serialization examples.
```javascript
const { create } = require('xmlbuilder2');
const xmlString = `
Tom Kazansky
Pete Mitchell
Nick Bradshaw
F-14 Tomcat
MiG-28
`;
const doc = create(xmlString);
```
--------------------------------
### Creating Processing Instruction Nodes in xmlbuilder2 vs xmlbuilder
Source: https://oozcitak.github.io/xmlbuilder2/upgrading-from-xmlbuilder
Shows the change in syntax for creating XML processing instruction nodes from JavaScript objects. xmlbuilder used keys starting with '?' for the instruction target. xmlbuilder2 uses a special '?' key where the value contains both the target and the content, or alternatively, the target can be specified as the key and the content as the value.
```javascript
// xmlbuilder
const builder = require("xmlbuilder");
const root = builder.create("root")
.ele({ "?target": "content" });
```
```javascript
// xmlbuilder2 equivalent
const { create } = require("xmlbuilder2");
const root = create().ele("root")
.ele({ "?": "target content" });
```
--------------------------------
### Add Attribute with Namespace using xmlbuilder2
Source: https://oozcitak.github.io/xmlbuilder2/namespaces
Shows how to add an XML attribute that belongs to a specific namespace using 'xmlbuilder2'. This example defines a namespace URI and applies it to a custom attribute named 'att' on the root element.
```javascript
const { create } = require('xmlbuilder2');
const ns1 = 'http://example.com/ns1'
const doc = create()
.ele('root').att(ns1, 'att', 'val').doc()
const xmlString = doc.end({ headless: true, prettyPrint: true });
console.log(xmlString);
```
--------------------------------
### Namespace Inheritance in xmlbuilder2
Source: https://oozcitak.github.io/xmlbuilder2/namespaces
Explains and demonstrates the automatic namespace inheritance feature in xmlbuilder2. Child elements created within a parent element automatically adopt the parent's namespace URI. This example shows how a child 'node' inherits the namespace 'http:/example.com' from its 'root' parent.
```javascript
const { create } = require('xmlbuilder2');
const root = create()
.ele('http:/example.com', 'root')
.ele('node')
.up();
const node = root.node.firstElementChild;
console.log(node.namespaceURI); // 'http:/example.com'
```
--------------------------------
### JS Object Comment Node Syntax: xmlbuilder vs xmlbuilder2
Source: https://oozcitak.github.io/xmlbuilder2/upgrading-from-xmlbuilder
Demonstrates the change in syntax for creating comment nodes from JS objects. In xmlbuilder, the key starts with '#comment', while in xmlbuilder2, it should be '!'. An alternative override method for xmlbuilder2 is also shown.
```javascript
const builder = require("xmlbuilder");
const root = builder.create("root")
.ele({ "#comment": "value" });
```
```javascript
const { create } = require("xmlbuilder2");
const root = document().ele("root")
.ele({ "!": "value" });
// or alternatively override the converter string
// note that we also override the text converter
// since it also begins with "#"
const root = create({ convert: { text: "#text", comment: "#comment" } })
.ele("root").ele({ "#comment": "value" });
```
--------------------------------
### Parse YAML Strings to XML with xmlbuilder2
Source: https://oozcitak.github.io/xmlbuilder2/parsing
Parses a YAML string, representing an XML structure, into an XML document. The 'create' function from 'xmlbuilder2' handles the YAML parsing. It's important that YAML strings start with '---' for correct recognition.
```javascript
const { create } = require('xmlbuilder2');
const yamlString =
`---
"topgun":
"pilots":
"pilot":
- "@callsign": "Iceman"
"@rank": "Lieutenant"
"#": "Tom Kazansky"
- "@callsign": "Maverick"
"@rank": "Lieutenant"
"#": "Pete Mitchell"
- "@callsign": "Goose"
"@rank": "Lieutenant (j.g.)"
"#": "Nick Bradshaw"
"hangar":
"aircraft":
- "F-14 Tomcat"
- "MiG-28"`
const doc = create(yamlString);
const xml = doc.end({ prettyPrint: true });
console.log(xml);
```
--------------------------------
### Get Root Element Node with root() - JavaScript
Source: https://oozcitak.github.io/xmlbuilder2/traversal-functions
The `root()` function returns the root element node of the XML document. It can be invoked from any node to get the top-level element.
```javascript
const { create } = require('xmlbuilder2');
const grandChild = create().ele("root").ele("child").ele("grandchild");
const root = grandchild.root();
```
--------------------------------
### Create Empty XML Document with Options
Source: https://oozcitak.github.io/xmlbuilder2/builder-functions
Creates an empty XML document with specific builder options, like encoding. The document is then serialized to a pretty-printed string.
```javascript
const { create } = require('xmlbuilder2');
const doc = create({ encoding: 'UTF-8' });
console.log(doc.end({ prettyPrint: true }));
```
--------------------------------
### Get Document Node with doc() - JavaScript
Source: https://oozcitak.github.io/xmlbuilder2/traversal-functions
The `doc()` function returns the document node. It can be called from any node within the document to access the root document.
```javascript
const { create } = require('xmlbuilder2');
const root = create().ele("root");
const doc = root.doc();
```
--------------------------------
### Create Empty XML Document
Source: https://oozcitak.github.io/xmlbuilder2/builder-functions
Creates a new, empty XML document using the default options. The document is then serialized to a pretty-printed string.
```javascript
const { create } = require('xmlbuilder2');
const doc = create();
console.log(doc.end({ prettyPrint: true }));
```
--------------------------------
### Get Parent Element Node with up() - JavaScript
Source: https://oozcitak.github.io/xmlbuilder2/traversal-functions
The `up()` function returns the parent element node of the current node. This is used to navigate upwards in the document tree towards the root.
```javascript
const { create } = require('xmlbuilder2');
const grandChild = create().ele("root").ele("child").ele("grandchild");
const child = grandchild.up();
const root = child.up();
```
--------------------------------
### Get Previous Sibling Node with prev() - JavaScript
Source: https://oozcitak.github.io/xmlbuilder2/traversal-functions
The `prev()` function returns the previous sibling node of the current node. This enables backward navigation among elements at the same level.
```javascript
const { create } = require('xmlbuilder2');
const root = create().ele("root")
.ele("node1").up()
.ele("node2").up();
const node2 = root.last();
const node1 = node2.prev();
```
--------------------------------
### Creating XML Document with xmlbuilder2 vs xmlbuilder
Source: https://oozcitak.github.io/xmlbuilder2/upgrading-from-xmlbuilder
Compares the creation of new XML documents using xmlbuilder and xmlbuilder2. xmlbuilder2 uses a single 'create' function to return an empty document node, whereas xmlbuilder had separate 'create' (for root element) and 'begin' (for empty document) functions. The xmlbuilder2 'create' function is chainable with element creation methods.
```javascript
// xmlbuilder
const builder = require("xmlbuilder");
const root = builder.create("root");
```
```javascript
// xmlbuilder2 equivalent
const { create } = require("xmlbuilder2");
const root = create().ele("root");
```
--------------------------------
### Get Next Sibling Node with next() - JavaScript
Source: https://oozcitak.github.io/xmlbuilder2/traversal-functions
The `next()` function returns the next sibling node of the current node. This allows for sequential navigation among elements at the same level.
```javascript
const { create } = require('xmlbuilder2');
const root = create().ele("root")
.ele("node1").up()
.ele("node2").up();
const node1 = root.first();
const node2 = node1.next();
```
--------------------------------
### Create Empty Document Fragment (Default Options)
Source: https://oozcitak.github.io/xmlbuilder2/builder-functions
Creates an empty document fragment using default options. Elements can be added programmatically after creation.
```javascript
const { fragment } = require('xmlbuilder2');
const frag = fragment();
frag.ele('node');
console.log(frag.toString({ prettyPrint: true }));
```
--------------------------------
### Get Last Child Node with last() - JavaScript
Source: https://oozcitak.github.io/xmlbuilder2/traversal-functions
The `last()` function returns the last child node of the current node. This is helpful for accessing the final element within a parent.
```javascript
const { create } = require('xmlbuilder2');
const root = create().ele("root")
.ele("node1").up()
.ele("node2").up();
const node2 = root.last();
```
--------------------------------
### Create Empty Document Fragment with Options
Source: https://oozcitak.github.io/xmlbuilder2/builder-functions
Creates an empty document fragment with the given options. This allows for programmatically adding elements to the fragment. It accepts builder options.
```javascript
const { fragment } = require('xmlbuilder2');
const frag = fragment({ encoding: 'UTF-8' });
frag.ele('node');
console.log(frag.toString({ prettyPrint: true }));
```
--------------------------------
### Get First Child Node with first() - JavaScript
Source: https://oozcitak.github.io/xmlbuilder2/traversal-functions
The `first()` function returns the first child node of the current node. This is useful for accessing the initial element within a parent.
```javascript
const { create } = require('xmlbuilder2');
const root = create().ele("root")
.ele("node1").up()
.ele("node2").up();
const node1 = root.first();
```
--------------------------------
### Create XML document using chainable API (Node.js)
Source: https://oozcitak.github.io/xmlbuilder2/index
Demonstrates how to create an XML document programmatically using the chainable API of xmlbuilder2. It shows element creation, attribute setting, text addition, and navigation using `up()` and `doc()`.
```javascript
const { create } = require('xmlbuilder2');
const doc = create({ version: '1.0' })
.ele('root', { att: 'val' })
.ele('foo')
.ele('bar').txt('foobar').up()
.up()
.ele('baz')
.doc();
console.log(doc.end({ prettyPrint: true }));
```
--------------------------------
### Declare Namespace Attribute in XML with xmlbuilder2
Source: https://oozcitak.github.io/xmlbuilder2/namespaces
Shows how to add a namespace declaration attribute to an XML element using 'xmlbuilder2'. This example declares both a default namespace and a prefixed namespace ('xsi') for schema location, then serializes the document.
```javascript
const { create } = require('xmlbuilder2');
const ns1 = 'http://example.com/ns1'
const xsi = 'http://www.w3.org/2001/XMLSchema-instance'
const doc = create().ele(ns1, 'root')
.att(xsi, 'xsi:schemaLocation', 'http://example.com/n1 schema.xsd')
.ele(ns1, 'foo').txt('bar').doc()
const xmlString = doc.end({ headless: true, prettyPrint: true });
console.log(xmlString);
```
--------------------------------
### Create Document Fragment with Content (Default Options)
Source: https://oozcitak.github.io/xmlbuilder2/builder-functions
Creates a new document fragment by parsing the content argument with default options. It accepts content as an XML/JSON string or a JS object.
```javascript
const { fragment } = require('xmlbuilder2');
const frag = fragment('foofoobar');
console.log(frag.toString({ prettyPrint: true }));
```
--------------------------------
### Create XML Document with Options and Content
Source: https://oozcitak.github.io/xmlbuilder2/builder-functions
Creates a new XML document by parsing provided content (XML string or JS object) with specified options, such as encoding. The resulting document is then serialized to a formatted string.
```javascript
const { create } = require('xmlbuilder2');
const doc = create({ encoding: "UTF-8" }, '');
console.log(doc.end({ prettyPrint: true }));
```
--------------------------------
### Create XML with Default Namespace using xmlbuilder2
Source: https://oozcitak.github.io/xmlbuilder2/namespaces
Demonstrates how to create an XML document with a default namespace declaration using the 'create' function from 'xmlbuilder2'. It defines a namespace URI and applies it to the root element and its children, then serializes the document to a string.
```javascript
const { create } = require('xmlbuilder2');
const ns1 = 'http://example.com/ns1';
const doc = create()
.ele(ns1, 'root')
.ele(ns1, 'foo').txt('bar').doc();
const xmlString = doc.end({ headless: true });
console.log(xmlString);
```
--------------------------------
### Builder Options
Source: https://oozcitak.github.io/xmlbuilder2/builder-functions
Configuration options for the XML builder, including settings for XML declaration, value conversions, and namespaces.
```APIDOC
## Builder Options
### Description
These options configure the behavior of the XML builder.
### Settings related to XML declaration
* `version` (string) - A version number string. Defaults to `'1.0'` if omitted.
* `encoding` (string) - Encoding declaration, e.g. `'UTF-8'`. No encoding declaration will be produced if omitted.
* `standalone` (boolean) - Standalone document declaration: `true` or `false`. No standalone document declaration will be produced if omitted.
__**Tip:** XML declaration can be specified later with the `dec` function.
### Settings related to value conversions
* `keepNullNodes` (boolean) - Whether nodes with `null` and `undefined` values will be kept or ignored. Defaults to `false`, which silently ignores nodes with `null` and `undefined` values. When set to `true`, `null` will be treated as an empty string.
* `keepNullAttributes` (boolean) - Whether attributes with `null` and `undefined` values will be kept or ignored. Defaults to `false`, which silently ignores attributes with `null` and `undefined` values. When set to `true`, `null` will be treated as an empty string.
* `ignoreConverters` (boolean) - Whether converter strings will be ignored when converting JS objects. Defaults to `false`.
* `convert` (object) - An object defining converter strings.
* `att` (string) - When prepended to a JS object key, converts its key-value pair to an attribute. Defaults to `'@'`.
* `ins` (string) - When prepended to a JS object key, converts its value to a processing instruction node. Defaults to `'?'`.
* `text` (string) - When prepended to a JS object key, converts its value to a text node. Defaults to `'#'`.
* `cdata` (string) - When prepended to a JS object key, converts its value to a CDATA section node. Defaults to `'$'`.
* `comment` (string) - When prepended to a JS object key, converts its value to a comment node. Defaults to `'!'`.
* `invalidCharReplacement` (string | function) - Defines a replacement value for invalid characters in input strings. If value is a string, each invalid character in an input string will be replaced with it; otherwise if value is a function it will be passed each invalid character and should return a replacement character. The arguments to the replacement function are: `char` (the invalid character to be replaced), `offset` (the offset of the invalid character), `str` (the input string).
__**Warning:** `invalidCharReplacement` is limited to the `Char` production in the XML spec. It doesn’t replace any other character.
* `parser` (object) - Defines custom parser functions.
* `parse` (function) - Main parser function.
* `docType` (function) - Creates a DocType node from parsed content.
* `comment` (function) - Creates a comment node from parsed content.
* `text` (function) - Creates a text node from parsed content.
* `instruction` (function) - Creates a processing instruction node from parsed content.
* `cdata` (function) - Creates a CData node from parsed content.
* `element` (function) - Creates an element node from parsed content.
* `attribute` (function) - Creates an attribute or namespace declaration from parsed content.
See custom parsers for more information and examples.
### Settings related to XML namespaces
* `defaultNamespace` (object) - Contains default namespaces to apply to all elements and attributes.
* `ele` (string) - Default namespace for element nodes.
* `att` (string) - Default namespace for attributes.
* `namespaceAlias` (object) - Contains namespace aliases where object keys are namespace aliases and object values are namespaces.
See example for usage.
```
--------------------------------
### Create XML Document in Chunks with createCB (Node.js)
Source: https://oozcitak.github.io/xmlbuilder2/builder-functions-with-callbacks
Demonstrates using `createCB` to serialize an XML document in chunks, writing to a file stream. The `data` callback is used to write each chunk, and the `end` callback is used to close the file stream. This approach is memory-efficient for large XML documents.
```javascript
const { createCB } = require('xmlbuilder2');
const { createWriteStream } = require('fs');
const filename = 'path/to/output/file';
const outFile = createWriteStream(filename);
const xmlBuilder = createCB({
'data': (chunk) => outFile.write(chunk),
'end': () => outFile.end(),
prettyPrint: true
});
xmlBuilder.ele('root')
.ele('foo').up()
.ele('bar').att('fizz', 'buzz').up()
.end();
```
--------------------------------
### Custom Parser: Skip Comment Nodes with xmlbuilder2
Source: https://oozcitak.github.io/xmlbuilder2/custom-parsers
This example demonstrates how to create a custom parser function in xmlbuilder2 to skip comment nodes during XML parsing. It shows the input XML string with comments and the resulting XML output after applying the custom parser.
```javascript
const { create } = require('xmlbuilder2');
const xmlString = `
`;
const doc = create({ parser: { comment: () => undefined } }, xmlString);
console.log(doc.end({ prettyPrint: true }));
```
--------------------------------
### Create XML Fragment in Chunks with fragmentCB (Node.js)
Source: https://oozcitak.github.io/xmlbuilder2/builder-functions-with-callbacks
Illustrates using `fragmentCB` to serialize an XML fragment in chunks. Similar to `createCB`, it writes to a file stream using `data` and `end` callbacks for efficient handling of large fragments.
```javascript
const { fragmentCB } = require('xmlbuilder2');
const { createWriteStream } = require('fs');
const filename = 'path/to/output/file';
const outFile = createWriteStream(filename);
const xmlBuilder = fragmentCB({
'data': (chunk) => outFile.write(chunk),
'end': () => outFile.end(),
prettyPrint: true
});
xmlBuilder.ele('foo').up()
.ele('foo').att('fizz', 'buzz').up()
.ele('foo').up()
.end();
```
--------------------------------
### Create XML Document from Content
Source: https://oozcitak.github.io/xmlbuilder2/builder-functions
Creates a new XML document by parsing the provided content (XML string or JS object) using default options. The resulting document is then serialized to a pretty-printed string.
```javascript
const { create } = require('xmlbuilder2');
const doc = create('foobar');
console.log(doc.end({ prettyPrint: true }));
```
--------------------------------
### Access DOM Node Interface with `node` Property
Source: https://oozcitak.github.io/xmlbuilder2/dom-interfaces
This example demonstrates how to access the DOM Node interface of an element created by xmlbuilder2. The `node` property of the builder object provides direct access to the underlying DOM Node, allowing you to retrieve properties like `tagName`.
```javascript
const { create } = require('xmlbuilder2');
const child = create().ele('root').ele('child');
const tagName = child.node.tagName;
```
--------------------------------
### Import Core xmlbuilder2 Functions
Source: https://oozcitak.github.io/xmlbuilder2/builder-functions
Imports the essential functions (create, fragment, convert, builder) from the xmlbuilder2 library for common XML building tasks.
```javascript
const { create, fragment, convert, builder } = require('xmlbuilder2');
```
--------------------------------
### Custom Element Parser: Handle Namespace Scopes with xmlbuilder2
Source: https://oozcitak.github.io/xmlbuilder2/custom-parsers
This example illustrates a custom element parser function for xmlbuilder2 that handles namespace scopes defined within the input object. It parses an object containing namespace declarations and generates XML with appropriate prefixed elements.
```javascript
const { create } = require('xmlbuilder2');
const obj = {
'root': {
'-ns1:some/uri': {
'node1': '',
'node2': ''
},
'-': {
'node3': ''
}
}
};
let prefix;
let ns;
const elementParser = function (parent, namespace, name) {
if (name.startsWith('-')) {
let [elePrefix, eleNS] = name.substring(1).split(':');
if (eleNS === undefined) {
prefix = undefined;
ns = undefined;
return parent;
}
else {
prefix = elePrefix;
ns = eleNS;
return parent.att('xmlns:' + prefix, eleNS);
}
}
else {
return prefix ? parent.ele(prefix + ':' + name) : parent.ele(name);
}
}
const doc = create({ parser: { element: elementParser } }, obj);
console.log(doc.end({ prettyPrint: true }));
```
--------------------------------
### Output Formatting: 'pretty' vs 'prettyPrint'
Source: https://oozcitak.github.io/xmlbuilder2/upgrading-from-xmlbuilder
Illustrates the renaming of the output formatting option from 'pretty' in xmlbuilder to 'prettyPrint' in xmlbuilder2 when using the end function.
```javascript
const builder = require("xmlbuilder");
const xml = builder.create("root")
.ele("foo")
.end({ pretty: true });
```
```javascript
const { create } = require("xmlbuilder2");
const xml = create().ele("root")
.ele("foo")
.end({ prettyPrint: true });
```
--------------------------------
### Create XML Element with Namespace
Source: https://oozcitak.github.io/xmlbuilder2/node-creation-functions-with-callbacks
Creates a new XML element with a specified namespace, tag name, and attributes. Requires the `xmlbuilder2` library. The output is a string representing the XML structure.
```javascript
const { createCB } = require('xmlbuilder2');
const xmlBuilder = createCB({
data: (chunk) => console.log(chunk),
end: () => { },
prettyPrint: true
});
xmlBuilder.ele('root')
.ele('http://example.com/ns1', 'child', { 'att': 'val' }).up()
.end();
```
--------------------------------
### Create XML Element with Namespace using xmlbuilder2
Source: https://oozcitak.github.io/xmlbuilder2/namespaces
Illustrates creating an SVG element with associated namespaces using 'xmlbuilder2'. It defines SVG and XLink namespaces, applies them to elements and attributes, and demonstrates how to explicitly declare namespace attributes.
```javascript
const { create } = require('xmlbuilder2');
const svgNs = 'http://www.w3.org/2000/svg'
const xlinkNs = 'http://www.w3.org/1999/xlink'
const doc = create().ele(svgNs, 'svg')
.att('http://www.w3.org/2000/xmlns/', 'xmlns:xlink', xlinkNs)
.ele(svgNs, 'script')
.att('type', 'text/ecmascript')
.att(xlinkNs, 'xlink:href', 'foo.js')
.doc()
const xmlString = doc.end({ headless: true, prettyPrint: true });
console.log(xmlString);
```
--------------------------------
### Set Default Namespaces for SVG/MathML using xmlbuilder2
Source: https://oozcitak.github.io/xmlbuilder2/namespaces
Demonstrates setting default namespaces for elements and attributes using 'xmlbuilder2', specifically for creating SVG documents. It configures the 'create' function with a default element namespace, enabling cleaner SVG creation without explicit namespace declarations for each element.
```javascript
const { create } = require('xmlbuilder2');
const svgDoc = create({ defaultNamespace: { ele: 'http://www.w3.org/2000/svg', att: null } });
// all svg elements below will be created in the 'http://www.w3.org/2000/svg' namespace
// all attributes will be created with the null namespace
svgDoc.ele('svg').att('viewBox', '0 0 100 100')
.ele('circle').att({ cx: 50, cy: 50, r: 48, fill: 'none', stroke: '#000' }).up()
.ele('path').att('d', 'M50,2a48,48 0 1 1 0,96a24 24 0 1 1 0-48a24 24 0 1 0 0-48').up()
.ele('circle').att({ cx: 50, cy: 26, r: 6 }).up()
.ele('circle').att({ cx: 50, cy: 74, r: 6, fill: '#FFF' }).up();
console.log(svgDoc.end({ prettyPrint: true }));
```
--------------------------------
### Create Processing Instructions from Array - xmlbuilder2
Source: https://oozcitak.github.io/xmlbuilder2/node-creation-functions
Creates new processing instructions from an array of strings, where each string contains a target and its content. These instructions are appended to the parent's child nodes, and the parent element is returned.
```javascript
const { create } = require('xmlbuilder2');
const root = create().ele('root')
.ins(['bar version="13.0"', 'bar public=true']);
console.log(root.end({ prettyPrint: true }));
```
--------------------------------
### createCB - Create XML Document in Chunks
Source: https://oozcitak.github.io/xmlbuilder2/builder-functions-with-callbacks
The `createCB` function serializes an XML document in chunks using provided callback functions. This is ideal for creating large XML documents without holding the entire structure in memory.
```APIDOC
## POST /createCB
### Description
Serializes an XML document in chunks with the provided callback functions. Useful for memory-efficient creation of large XML documents.
### Method
POST
### Endpoint
/createCB
### Parameters
#### Query Parameters
None
#### Request Body
- **options** (object) - Required - Builder options and callback functions.
- **data** (function) - Optional - Called when a chunk of XML is serialized. Receives chunk (string) and depth (number).
- **end** (function) - Optional - Called when XML serialization is completed.
- **error** (function) - Optional - Called when an error occurs. Receives error object.
- **prettyPrint** (boolean) - Optional - If true, formats the XML output.
### Request Example
```javascript
const { createCB } = require('xmlbuilder2');
const { createWriteStream } = require('fs');
const filename = 'path/to/output/file';
const outFile = createWriteStream(filename);
const xmlBuilder = createCB({
'data': (chunk) => outFile.write(chunk),
'end': () => outFile.end(),
prettyPrint: true
});
xmlBuilder.ele('root')
.ele('foo').up()
.ele('bar').att('fizz', 'buzz').up()
.end();
```
### Response
#### Success Response (200)
XML document serialized in chunks.
#### Response Example
```xml
```
```
--------------------------------
### Wrap Existing DOM Node with Builder (with options)
Source: https://oozcitak.github.io/xmlbuilder2/builder-functions
Wraps an existing DOM node with specified options and returns a builder object. This allows for manipulation and creation of XML structures based on a pre-existing DOM node. It takes options for builder configuration and the DOM node to wrap.
```javascript
const { builder } = require('xmlbuilder2');
const node = document.createElement('node');
const xml = builder({ version: '1.0' }, node)
.ele('child')
.end({ prettyPrint: true });
console.log(xml);
```
--------------------------------
### Text Node Creation API
Source: https://oozcitak.github.io/xmlbuilder2/node-creation-functions-with-callbacks
The `txt` method in XMLBuilder2 is used to create and serialize a new text node.
```APIDOC
## txt (content)
### Description
Creates and serializes a new text node.
### Method
`txt`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
* **content** (string) - Required - The content of the text node.
### Request Example
```javascript
const { createCB } = require('xmlbuilder2');
const xmlBuilder = createCB({
data: (chunk) => console.log(chunk),
end: () => { },
prettyPrint: true
});
xmlBuilder.ele('root').txt('val').end();
```
### Response
#### Success Response (200)
* **XML String** - The serialized XML string.
#### Response Example
```xml
val
```
```
--------------------------------
### Builder Functions
Source: https://oozcitak.github.io/xmlbuilder2/builder-functions
These functions are typically imported with `const { create, fragment, convert, builder } = require('xmlbuilder2');` and are used for creating and manipulating XML documents.
```APIDOC
## create
### Description
The `create` function creates and returns a new XML document. It can be used to create an empty document, or to parse XML/JSON content into a document node.
### Method
`create(options?: object, contents?: string | object)`
`create(options?: object)`
`create(contents?: string | object)`
`create()`
### Parameters
#### create(options: object, contents: string | object)
* **options** (object) - Builder options for customizing document creation.
* **contents** (string | object) - A string containing XML or JSON, or a JS object representing nodes to insert.
#### create(options: object)
* **options** (object) - Builder options for customizing document creation.
#### create(contents: string | object)
* **contents** (string | object) - A string containing XML or JSON, or a JS object representing nodes to insert.
#### create()
No parameters.
### Request Example
```javascript
const { create } = require('xmlbuilder2');
// Example 1: Creating with options and content
const doc1 = create({ encoding: "UTF-8" }, '');
console.log(doc1.end({ prettyPrint: true }));
// Example 2: Creating with options only
const doc2 = create({ encoding: 'UTF-8' });
console.log(doc2.end({ prettyPrint: true }));
// Example 3: Creating with content only
const doc3 = create('foobar');
console.log(doc3.end({ prettyPrint: true }));
// Example 4: Creating an empty document
const doc4 = create();
console.log(doc4.end({ prettyPrint: true }));
```
### Response
Returns a document node representing the created or parsed XML document.
#### Success Response (200)
* **document node** (object) - The root node of the XML document.
#### Response Example
```xml
```
```xml
```
```xml
foobar
```
```xml
```
```
--------------------------------
### fragmentCB - Create XML Fragment in Chunks
Source: https://oozcitak.github.io/xmlbuilder2/builder-functions-with-callbacks
The `fragmentCB` function serializes an XML document fragment in chunks using callback functions. Similar to `createCB` but for fragments instead of a complete document.
```APIDOC
## POST /fragmentCB
### Description
Serializes an XML document fragment in chunks with the provided callback functions. Suitable for creating sequences of XML elements without a single root.
### Method
POST
### Endpoint
/fragmentCB
### Parameters
#### Query Parameters
None
#### Request Body
- **options** (object) - Required - Builder options and callback functions.
- **data** (function) - Optional - Called when a chunk of XML is serialized. Receives chunk (string) and depth (number).
- **end** (function) - Optional - Called when XML serialization is completed.
- **error** (function) - Optional - Called when an error occurs. Receives error object.
- **prettyPrint** (boolean) - Optional - If true, formats the XML output.
### Request Example
```javascript
const { fragmentCB } = require('xmlbuilder2');
const { createWriteStream } = require('fs');
const filename = 'path/to/output/file';
const outFile = createWriteStream(filename);
const xmlBuilder = fragmentCB({
'data': (chunk) => outFile.write(chunk),
'end': () => outFile.end(),
prettyPrint: true
});
xmlBuilder.ele('foo').up()
.ele('foo').att('fizz', 'buzz').up()
.ele('foo').up()
.end();
```
### Response
#### Success Response (200)
XML fragment serialized in chunks.
#### Response Example
```xml
```
```
--------------------------------
### XML Namespace Support: xmlbuilder2
Source: https://oozcitak.github.io/xmlbuilder2/upgrading-from-xmlbuilder
Shows how to specify XML namespaces when creating elements and attributes in xmlbuilder2 using an optional argument in the `ele` and `att` functions.
```javascript
const { create } = require('xmlbuilder2');
const root = create().ele('http://example.com/ns1', 'root');
```
--------------------------------
### Convert JS Object to XML Processing Instruction using '?'
Source: https://oozcitak.github.io/xmlbuilder2/object-conversion
Illustrates using the default converter string '?' to create XML processing instruction nodes. The key '?' defines the instruction target, and its value is the instruction content. Requires the 'create' function from 'xmlbuilder'.
```javascript
obj = {
'?': 'background classified ref="NAM#123456"',
pilot: 'Pete Mitchell'
}
// This becomes:
//
// Pete Mitchell
```
--------------------------------
### builder function with options
Source: https://oozcitak.github.io/xmlbuilder2/builder-functions
The `builder` function can wrap an existing DOM node with custom options to create a builder object for XML construction.
```APIDOC
## builder(options, node)
### Description
Wraps an existing DOM node with the given `options` and returns a builder object.
### Method
`builder(options: object, node: Node)`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
* `options` (object) - Builder options. See 'Builder options' section for details.
* `node` (Node) - A DOM node to wrap.
### Request Example
```javascript
const { builder } = require('xmlbuilder2');
const node = document.createElement('node');
const xml = builder({ version: '1.0' }, node)
.ele('child')
.end({ prettyPrint: true });
console.log(xml);
```
### Response
#### Success Response (200)
Returns the XML string generated from the builder.
#### Response Example
```xml
```
```
--------------------------------
### Use Built-in Namespace Aliases in xmlbuilder2
Source: https://oozcitak.github.io/xmlbuilder2/namespaces
Demonstrates how to use built-in namespace aliases like '@xml' for elements and attributes in xmlbuilder2. This simplifies XML creation by avoiding the need to declare common namespaces explicitly. It shows the resulting XML string with the aliased namespaces applied.
```javascript
const { create } = require('xmlbuilder2');
const ele = create().ele('@xml', 'root').att('@xml', 'att', 'val');
console.log(ele.toString()); // ''
```
--------------------------------
### Convert Content to XML (Default Options)
Source: https://oozcitak.github.io/xmlbuilder2/builder-functions
Converts a JS object or XML/JSON string into an XML document string using default builder options. The output is the default XML format.
```javascript
const { convert } = require('xmlbuilder2');
const xml = convert({ root: { node: { } });
console.log(xml);
```
--------------------------------
### Document Fragment Creation and Parsing: xmlbuilder2
Source: https://oozcitak.github.io/xmlbuilder2/upgrading-from-xmlbuilder
Illustrates the creation and parsing of document fragment nodes in xmlbuilder2 using the `fragment` function with XML strings, JS objects, and JSON strings.
```javascript
const { fragment } = require('xmlbuilder2');
// create a document fragment node
const frag = fragment().ele("node").up().ele("node", { att: "val" }).up();
// parse a fragment from an XML document string
const xmlStr = '';
const frag = fragment(xmlStr);
// parse a JS object
const xmlObj = { node: [ {}, { "@att": "val"} ] };
const frag = fragment(xmlObj);
// parse a JSON string
const jsonStr = `{ "node": [ {}, { "@att": "val"} ] }`;
const frag = fragment(jsonStr);
```
--------------------------------
### Element Creation API
Source: https://oozcitak.github.io/xmlbuilder2/node-creation-functions-with-callbacks
The `ele` method in XMLBuilder2 is used to create and serialize new element nodes. It supports creating elements with namespaces, attributes, or by converting JavaScript objects and strings.
```APIDOC
## ele (namespace, name, attributes?)
### Description
Creates a new element node with the given namespace URI, tag name, and attributes.
### Method
`ele`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
* **namespace** (string) - Required - The namespace URI for the element.
* **name** (string) - Required - The tag name for the element.
* **attributes** (object) - Optional - A JS object containing key/value pairs of element attributes.
### Request Example
```javascript
const { createCB } = require('xmlbuilder2');
const xmlBuilder = createCB({
data: (chunk) => console.log(chunk),
end: () => { },
prettyPrint: true
});
xmlBuilder.ele('root')
.ele('http://example.com/ns1', 'child', { 'att': 'val' }).up()
.end();
```
### Response
#### Success Response (200)
* **XML String** - The serialized XML string.
#### Response Example
```xml
```
## ele (name, attributes?)
### Description
Creates a new element node with the given tag name and attributes.
### Method
`ele`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
* **name** (string) - Required - The tag name for the element.
* **attributes** (object) - Optional - A JS object containing key/value pairs of element attributes.
### Request Example
```javascript
const { createCB } = require('xmlbuilder2');
const xmlBuilder = createCB({
data: (chunk) => console.log(chunk),
end: () => { },
prettyPrint: true
});
xmlBuilder.ele('root')
.ele('child', { 'att': 'val' }).up()
.end();
```
### Response
#### Success Response (200)
* **XML String** - The serialized XML string.
#### Response Example
```xml
```
## ele (contents)
### Description
Creates a new element node by converting the given JS object into XML nodes or parsing a string containing an XML document.
### Method
`ele`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
* **contents** (string | object) - Required - A JS object representing nodes to insert or a string containing an XML document in either XML or JSON format.
### Request Example (JS Object)
```javascript
const { createCB } = require('xmlbuilder2');
const xmlBuilder = createCB({
data: (chunk) => console.log(chunk),
end: () => { },
prettyPrint: true
});
xmlBuilder.ele('root')
.ele({
foo: {
bar: 'foobar'
},
baz: ''
}).end();
```
### Response Example (JS Object)
```xml
foobar
```
### Request Example (String)
```javascript
const { createCB } = require('xmlbuilder2');
const xmlBuilder = createCB({
data: (chunk) => console.log(chunk),
end: () => { },
prettyPrint: true
});
xmlBuilder.ele('root')
.ele('foobar')
.end();
```
### Response Example (String)
```xml
foobar
```
```
--------------------------------
### builder function without options
Source: https://oozcitak.github.io/xmlbuilder2/builder-functions
The `builder` function can wrap an existing DOM node with default options to create a builder object for XML construction.
```APIDOC
## builder(node)
### Description
Wraps an existing DOM node with the default options and returns a builder object.
### Method
`builder(node: Node)`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
* `node` (Node) - A DOM node to wrap.
### Request Example
```javascript
const { builder } = require('xmlbuilder2');
const node = document.createElement('node');
const xml = builder(node)
.ele('child')
.end({ prettyPrint: true });
console.log(xml);
```
### Response
#### Success Response (200)
Returns the XML string generated from the builder.
#### Response Example
```xml
```
```