Simple XML to JavaScript object converter.
XML generation functionality for converting JavaScript objects to well-formed XML strings with customizable formatting and structure options.
Main class for converting JavaScript objects to XML strings with extensive configuration options for output formatting and structure.
/**
* XML Builder class for converting JavaScript objects to XML
*/
class Builder {
/**
* Create a new Builder instance
* @param options - Builder configuration options
*/
constructor(options?: BuilderOptions);
/**
* Convert JavaScript object to XML string
* @param rootObj - JavaScript object to convert
* @returns XML string representation
*/
buildObject(rootObj: any): string;
}Usage Examples:
const xml2js = require('xml2js');
// Basic XML building
const builder = new xml2js.Builder();
const obj = {
person: {
name: 'John Doe',
age: 30,
active: true
}
};
const xml = builder.buildObject(obj);
console.log(xml);
// Output:
// <?xml version="1.0" encoding="UTF-8"?>
// <person>
// <name>John Doe</name>
// <age>30</age>
// <active>true</active>
// </person>
// Building with attributes
const objWithAttrs = {
product: {
$: { id: '123', category: 'electronics' },
name: 'Laptop',
price: 999.99
}
};
const xmlWithAttrs = builder.buildObject(objWithAttrs);
console.log(xmlWithAttrs);
// Output:
// <?xml version="1.0" encoding="UTF-8"?>
// <product id="123" category="electronics">
// <name>Laptop</name>
// <price>999.99</price>
// </product>const xml2js = require('xml2js');
// Custom builder configuration
const customBuilder = new xml2js.Builder({
rootName: 'catalog',
headless: false,
xmldec: {
version: '1.0',
encoding: 'UTF-8',
standalone: true
},
renderOpts: {
pretty: true,
indent: ' ', // 4 spaces
newline: '\n'
},
cdata: true
});
const catalogData = {
item: [
{
$: { id: '1' },
title: 'Product One',
description: 'This contains <special> characters & symbols'
},
{
$: { id: '2' },
title: 'Product Two',
description: 'Another product description'
}
]
};
const catalogXml = customBuilder.buildObject(catalogData);
console.log(catalogXml);interface BuilderOptions {
/** Prefix for accessing XML attributes (default: '$') */
attrkey?: string;
/** Prefix for accessing character content (default: '_') */
charkey?: string;
/** Root element name when not specified in object (default: 'root') */
rootName?: string;
/** Omit XML declaration (default: false) */
headless?: boolean;
/** Allow Unicode surrogate characters (default: false) */
allowSurrogateChars?: boolean;
/** Wrap text in CDATA sections when needed (default: false) */
cdata?: boolean;
}interface XMLDeclarationOptions {
/** XML declaration attributes */
xmldec?: {
/** XML version (default: '1.0') */
version?: string;
/** Character encoding (default: 'UTF-8') */
encoding?: string;
/** Standalone document declaration (default: true) */
standalone?: boolean;
};
}interface RenderingOptions {
/** XML formatting options */
renderOpts?: {
/** Pretty-print XML (default: true) */
pretty?: boolean;
/** Indentation string (default: ' ') */
indent?: string;
/** Newline character (default: '\n') */
newline?: string;
};
/** Optional DTD declaration (default: null) */
doctype?: any;
}Usage Examples:
const xml2js = require('xml2js');
// Compact XML output
const compactBuilder = new xml2js.Builder({
renderOpts: {
pretty: false
}
});
// Custom indentation
const tabBuilder = new xml2js.Builder({
renderOpts: {
pretty: true,
indent: '\t', // Use tabs instead of spaces
newline: '\r\n' // Windows line endings
}
});
// Headless XML (no declaration)
const headlessBuilder = new xml2js.Builder({
headless: true,
rootName: 'data'
});
const simpleObj = { message: 'Hello World' };
console.log(headlessBuilder.buildObject(simpleObj));
// Output: <data><message>Hello World</message></data>
// CDATA handling
const cdataBuilder = new xml2js.Builder({
cdata: true
});
const objWithSpecialChars = {
content: 'This contains <tags> and & special characters'
};
console.log(cdataBuilder.buildObject(objWithSpecialChars));
// Output includes CDATA sections for text with special charactersconst xml2js = require('xml2js');
const builder = new xml2js.Builder();
// Object with attributes using $ key
const productWithAttrs = {
product: {
$: {
id: 'P001',
category: 'electronics',
inStock: true
},
name: 'Smartphone',
price: {
$: { currency: 'USD' },
_: 599.99
},
specifications: {
screen: '6.1 inches',
storage: '128GB',
color: 'Black'
}
}
};
const xml = builder.buildObject(productWithAttrs);
console.log(xml);const xml2js = require('xml2js');
const builder = new xml2js.Builder();
// Arrays create multiple elements
const booksData = {
library: {
book: [
{
$: { isbn: '978-0123456789' },
title: 'JavaScript Guide',
author: 'John Smith',
year: 2023
},
{
$: { isbn: '978-0987654321' },
title: 'Node.js Handbook',
author: 'Jane Doe',
year: 2023
}
]
}
};
const libraryXml = builder.buildObject(booksData);
console.log(libraryXml);const xml2js = require('xml2js');
const builder = new xml2js.Builder({
charkey: '_'
});
// Mixed content with text and child elements
const articleData = {
article: {
$: { id: 'art-001' },
title: 'Understanding XML',
content: {
paragraph: [
{
_: 'This is the first paragraph with ',
emphasis: 'emphasized text',
_2: ' and more content.'
},
'This is a simple second paragraph.'
]
},
author: 'Technical Writer'
}
};
const articleXml = builder.buildObject(articleData);
console.log(articleXml);const xml2js = require('xml2js');
const builder = new xml2js.Builder({
xmldec: {
version: '1.0',
encoding: 'UTF-8'
}
});
// XML with namespaces
const namespacedData = {
'soap:Envelope': {
$: {
'xmlns:soap': 'http://schemas.xmlsoap.org/soap/envelope/',
'xmlns:web': 'http://example.com/webservice'
},
'soap:Header': {},
'soap:Body': {
'web:GetUserRequest': {
'web:UserId': '12345'
}
}
}
};
const soapXml = builder.buildObject(namespacedData);
console.log(soapXml);The Builder class provides straightforward error handling through exceptions:
const xml2js = require('xml2js');
const builder = new xml2js.Builder();
try {
// Attempt to build XML from invalid data
const invalidData = {
// Some problematic data structure
};
const xml = builder.buildObject(invalidData);
console.log('XML generated successfully:', xml);
} catch (error) {
console.error('XML building failed:', error.message);
// Handle the error appropriately
}const xml2js = require('xml2js');
// Parse and then rebuild XML
async function roundTripXML(xmlString) {
try {
// Parse XML with specific options
const parseOptions = {
explicitArray: false,
mergeAttrs: false,
explicitCharkey: false
};
const parsed = await xml2js.parseStringPromise(xmlString, parseOptions);
// Build XML with matching options
const builder = new xml2js.Builder({
attrkey: '$',
charkey: '_',
headless: false
});
const rebuiltXml = builder.buildObject(parsed);
return rebuiltXml;
} catch (error) {
console.error('Round-trip conversion failed:', error);
throw error;
}
}Install with Tessl CLI
npx tessl i tessl/npm-xml2js