Huskie69
Huskie69

Reputation: 865

Convert JavaScript object (array) to XML

I have JavaScript object which is formatted as JSON using this code:

obj.push({      
    lat: (lat / 1e5).toFixed(5),
    lon: (lon / 1e5).toFixed(5),
    ele: "0"
});

This object/array can contain potentially hundereds of indiviual objects/properties which look like this:

 [{"lat":"32.71883","lon":"-16.76118","ele":"0"},{"lat":"32.71882","lon":"-16.76138","ele":"0"},{"lat":"32.71881","lon":"-16.76159","ele":"0"},{"lat":"32.71880","lon":"-16.76179","ele":"0"},{"lat":"32.71879","lon":"-16.76199","ele":"0"},{"lat":"32.71878","lon":"-16.76220","ele":"0"}....]

I'd like to convert this object to XML using the correct element tags in the following format:

<trkpt lat="32.7188300" lon="-16.7611800">   // note how this lumps together two separate properties into a single element
 <ele>0</ele>
</trkpt>

I've found a snippet of code to tranform the object:

function objectToXml(object) {
        var xml = '';
        for (var prop in object) {
            if (!object.hasOwnProperty(prop)) {
                continue;
            }
            if (object[prop] == undefined)
                continue;
            xml += "<" + prop + ">";
            if (typeof object[prop] == "object")
                xml += objectToXml(new Object(object[prop]));
            else
                xml += object[prop];
            xml += "<!--" + prop + "--\>";
        }
        return xml;
    }

This certainly converts the object to some extent, however, it tries to create a key for each property set, an concatenates the properties into one string.

  <0>32.71883-16.761180<1>32.71882-16.761380<2>32.71881-16.761590<3>32.71880-16.761790<4>.....

Any suggestions on how I can use this function to correctly format the XML as described?

Upvotes: 1

Views: 16579

Answers (1)

mpm
mpm

Reputation: 20155

You could do that with string templates

const data = [{
  "lat": "32.71883",
  "lon": "-16.76118",
  "ele": "0"
}, {
  "lat": "32.71882",
  "lon": "-16.76138",
  "ele": "0"
}, {
  "lat": "32.71881",
  "lon": "-16.76159",
  "ele": "0"
}, {
  "lat": "32.71880",
  "lon": "-16.76179",
  "ele": "0"
}, {
  "lat": "32.71879",
  "lon": "-16.76199",
  "ele": "0"
}, {
  "lat": "32.71878",
  "lon": "-16.76220",
  "ele": "0"
}]



const toXml = (data) => {
  return data.reduce((result, el) => {
   return result + `<trkpt lat="${el.lat}" lon="${el.lon}"><ele>${el.ele}</ele></trkpt>\n`
  }, '')
}

console.log(toXml(data))

Upvotes: 1

Related Questions