How can I convert an object to an XML string in JavaScript?
Benjamin C
benjamin c profile pic

Converting an object to an XML string in JavaScript involves transforming the object's data structure into XML syntax. There are different approaches you can take, depending on your requirements and the complexity of the object. Here's a commonly used method: 1. Using a recursive approach: You can recursively traverse the object and its properties to build the XML string. Each property becomes an XML element, and their values can be nested elements or attributes. Here's an example implementation:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38

function objectToXml(obj, rootName = 'root') {
  let xml = '';

  const buildXml = (data, nodeName) => {
    let innerXml = '';

    if (typeof data === 'object') {
      for (const key in data) {
        if (data.hasOwnProperty(key)) {
          innerXml += buildXml(data[key], key);
        }
      }
    } else {
      innerXml = data;
    }

    return `<${nodeName}>${innerXml}</${nodeName}>`;
  };

  xml += buildXml(obj, rootName);

  return xml;
}

// Example usage
const data = {
  name: 'John Doe',
  age: 30,
  address: {
    street: '123 Main St',
    city: 'Example City',
    country: 'Example Country'
  }
};

const xmlString = objectToXml(data, 'person');
console.log(xmlString);

In this example, theobjectToXml function takes an objectobj and an optionalrootName parameter representing the root element name in the resulting XML string. It defines a helper functionbuildXml that recursively traverses the object and its properties. If a property is an object, it recursively callsbuildXml with the nested data and key. If a property is a simple value, it assigns it directly to the inner XML. The function builds the XML string by concatenating the XML syntax using template literals. The resulting XML string will be:

xml John Doe 30

123 Main St Example City Example Country

Please note that this approach is a basic implementation and may not handle all possible object structures or complex XML requirements. For more advanced XML manipulation, you may consider using libraries or dedicated XML conversion tools available in JavaScript.