Converts JavaScript objects to XML strings with comprehensive formatting and structure control options. Supports both compact single-line output and pretty-printed formatted XML.
Main builder class that converts JavaScript objects into XML strings with customizable building behavior.
/**
* Creates a new XMLBuilder instance with optional configuration
* @param options - Builder configuration options
*/
class XMLBuilder {
constructor(options?: XmlBuilderOptions);
}Converts JavaScript objects to XML strings.
/**
* Converts JavaScript object to XML string
* @param jObj - JavaScript object to convert
* @returns XML string representation
*/
build(jObj: any): string;Usage Examples:
import { XMLBuilder } from "fast-xml-parser";
// Basic building
const builder = new XMLBuilder();
const obj = { root: { item: "value" } };
const xml = builder.build(obj);
console.log(xml); // <root><item>value</item></root>
// With formatting
const prettyBuilder = new XMLBuilder({ format: true, indentBy: " " });
const prettyXml = prettyBuilder.build(obj);
/*
<root>
<item>value</item>
</root>
*/
// With attributes
const attrObj = {
root: {
"@_id": "123",
"@_name": "test",
"#text": "content"
}
};
const attrBuilder = new XMLBuilder({ ignoreAttributes: false });
const attrXml = attrBuilder.build(attrObj);
// <root id="123" name="test">content</root>Comprehensive configuration interface for XMLBuilder with extensive customization options.
interface XmlBuilderOptions {
/** Give a prefix to the attribute name in the resulting JS object */
attributeNamePrefix?: string;
/** A name to group all attributes of a tag under, or false to disable */
attributesGroupName?: false | string;
/** The name of the text node in the resulting JS */
textNodeName?: string;
/** Whether to ignore attributes when building */
ignoreAttributes?: boolean | (string | RegExp)[] | ((attrName: string, jPath: string) => boolean);
/** Give a property name to set CDATA values to instead of merging to tag's text value */
cdataPropName?: false | string;
/** If set, parse comments and set as this property */
commentPropName?: false | string;
/** Whether to make output pretty instead of single line */
format?: boolean;
/** If format is set to true, sets the indent string */
indentBy?: string;
/** Give a name to a top-level array */
arrayNodeName?: string;
/** Create empty tags for tags with no text value */
suppressEmptyNode?: boolean;
/** Suppress an unpaired tag */
suppressUnpairedNode?: boolean;
/** Don't put a value for boolean attributes */
suppressBooleanAttributes?: boolean;
/** Preserve the order of tags in resulting JS object */
preserveOrder?: boolean;
/** List of tags without closing tags */
unpairedTags?: string[];
/** Nodes to stop parsing at */
stopNodes?: string[];
/** Control how tag value should be processed */
tagValueProcessor?: (name: string, value: unknown) => unknown;
/** Control how attribute value should be processed */
attributeValueProcessor?: (name: string, value: unknown) => unknown;
/** Whether to process default and DOCTYPE entities */
processEntities?: boolean;
/** Special list grouping handling */
oneListGroup?: boolean;
}import { XMLBuilder } from "fast-xml-parser";
const builder = new XMLBuilder();
// Simple object
const simple = { greeting: "Hello World" };
console.log(builder.build(simple));
// <greeting>Hello World</greeting>
// Nested objects
const nested = {
person: {
name: "John",
age: 30,
address: {
street: "123 Main St",
city: "Boston"
}
}
};
const xml = builder.build(nested);
/*
<person>
<name>John</name>
<age>30</age>
<address>
<street>123 Main St</street>
<city>Boston</city>
</address>
</person>
*/import { XMLBuilder } from "fast-xml-parser";
// Attributes with default prefix
const attrBuilder = new XMLBuilder({ ignoreAttributes: false });
const objWithAttrs = {
book: {
"@_id": "123",
"@_isbn": "978-0123456789",
title: "XML Processing",
author: "John Doe"
}
};
const xml = attrBuilder.build(objWithAttrs);
// <book id="123" isbn="978-0123456789"><title>XML Processing</title><author>John Doe</author></book>
// Custom attribute prefix
const customBuilder = new XMLBuilder({
ignoreAttributes: false,
attributeNamePrefix: "$$"
});
const customObj = {
item: {
"$$class": "highlight",
"$$data-value": "important",
"#text": "Content"
}
};
// <item class="highlight" data-value="important">Content</item>import { XMLBuilder } from "fast-xml-parser";
const groupedBuilder = new XMLBuilder({
ignoreAttributes: false,
attributesGroupName: "attrs"
});
const groupedObj = {
element: {
attrs: {
id: "main",
class: "container"
},
"#text": "Content"
}
};
const xml = groupedBuilder.build(groupedObj);
// <element id="main" class="container">Content</element>import { XMLBuilder } from "fast-xml-parser";
const builder = new XMLBuilder();
// Arrays become multiple tags
const arrayObj = {
root: {
item: ["apple", "banana", "cherry"]
}
};
const xml = builder.build(arrayObj);
/*
<root>
<item>apple</item>
<item>banana</item>
<item>cherry</item>
</root>
*/
// Array with wrapper
const wrapperBuilder = new XMLBuilder({ arrayNodeName: "items" });
const wrappedArray = ["apple", "banana", "cherry"];
const wrappedXml = wrapperBuilder.build(wrappedArray);
/*
<items>
<item>apple</item>
<item>banana</item>
<item>cherry</item>
</items>
*/import { XMLBuilder } from "fast-xml-parser";
const prettyBuilder = new XMLBuilder({
format: true,
indentBy: " " // 2 spaces
});
const complex = {
catalog: {
"@_version": "1.0",
books: {
book: [
{
"@_id": "1",
title: "XML Guide",
price: 29.99
},
{
"@_id": "2",
title: "JSON Handbook",
price: 24.99
}
]
}
}
};
const prettyXml = prettyBuilder.build(complex);
/*
<catalog version="1.0">
<books>
<book id="1">
<title>XML Guide</title>
<price>29.99</price>
</book>
<book id="2">
<title>JSON Handbook</title>
<price>24.99</price>
</book>
</books>
</catalog>
*/import { XMLBuilder } from "fast-xml-parser";
const specialBuilder = new XMLBuilder({
cdataPropName: "#cdata",
commentPropName: "#comment"
});
const specialObj = {
document: {
"#comment": "This is a comment",
content: {
"#cdata": "<script>alert('hello');</script>"
}
}
};
const xml = specialBuilder.build(specialObj);
/*
<document>
<!-- This is a comment -->
<content><![CDATA[<script>alert('hello');</script>]]></content>
</document>
*/import { XMLBuilder } from "fast-xml-parser";
const htmlBuilder = new XMLBuilder({
ignoreAttributes: false,
suppressEmptyNode: true,
suppressBooleanAttributes: false,
unpairedTags: ['br', 'hr', 'img', 'input']
});
const htmlObj = {
form: {
input: [
{
"@_type": "text",
"@_name": "username",
"@_required": true
},
{
"@_type": "submit",
"@_value": "Submit"
}
],
br: ""
}
};
const html = htmlBuilder.build(htmlObj);
/*
<form>
<input type="text" name="username" required />
<input type="submit" value="Submit" />
<br />
</form>
*/import { XMLBuilder } from "fast-xml-parser";
const processingBuilder = new XMLBuilder({
tagValueProcessor: (tagName, value) => {
if (tagName === 'price' && typeof value === 'number') {
return `$${value.toFixed(2)}`;
}
return value;
},
attributeValueProcessor: (attrName, value) => {
if (attrName === 'id') {
return `item-${value}`;
}
return value;
}
});
const processObj = {
product: {
"@_id": "123",
name: "Widget",
price: 19.99
}
};
const xml = processingBuilder.build(processObj);
// <product id="item-123"><name>Widget</name><price>$19.99</price></product>import { XMLBuilder } from "fast-xml-parser";
const entityBuilder = new XMLBuilder({ processEntities: true });
const entityObj = {
text: "Cats & Dogs > Birds < Fish"
};
const xml = entityBuilder.build(entityObj);
// <text>Cats & Dogs > Birds < Fish</text>