How to use the Builder function from xml2js

Find comprehensive JavaScript xml2js.Builder code examples handpicked from public code repositorys.

xml2js.Builder is a class in the xml2js library that creates an XML builder that can convert JavaScript objects into corresponding XML documents.

357
358
359
360
361
362
363
364
365
366
// console.log("protojson:")
// console.log(protojson)

let xmlDetail
try {
  xmlDetail = new xml2js.Builder(options).buildObject(cotjson.event.detail)
  protojson.cotEvent.xmlDetail = xmlDetail.replace(`<${options.rootName}>`, '').replace(`</${options.rootName}>`, '')
} catch (err) {
  console.error("Error converting detail to xmlDetail:")
  console.error(err);
fork icon2
star icon4
watch icon2

+ 9 other calls in file

1816
1817
1818
1819
1820
1821
1822
1823
1824
    finalEntries.push({ product: newEntry })
}

console.log(finalEntries.length)

var builder = new xml2js.Builder();
var xml = builder.buildObject({ products: finalEntries });

// console.log(xml)
fork icon0
star icon0
watch icon1

How does xml2js.Builder work?

xml2js.Builder is a class in the xml2js library that can be used to create a new XML builder instance that is capable of parsing JavaScript objects into XML strings using various options and settings. When a new instance of the xml2js.Builder class is created, it can be used to configure the behavior of the resulting XML output, such as setting the name of the root element, controlling the indentation level, and more. Once configured, the xml2js.Builder instance can be used to convert JavaScript objects to XML strings by calling the buildObject() method with the object to be converted as its argument.

Ai Example

1
2
3
4
5
6
7
8
9
10
11
12
const xml2js = require("xml2js");

const obj = {
  fruits: {
    fruit: ["apple", "banana", "orange"],
  },
};

const builder = new xml2js.Builder();
const xml = builder.buildObject(obj);

console.log(xml);

In this example, we first define a JavaScript object obj with a nested fruits object containing an array of fruits. We then create a new xml2js.Builder object called builder and use the buildObject() method to convert the obj object to an XML string called xml. Finally, we log the XML string to the console.