将JavaScript对象(数组)转换为XML

时间:2018-09-13 10:14:41

标签: javascript arrays json xml

我有一个JavaScript对象,使用以下代码将其格式化为JSON:

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

此对象/数组可能包含潜在的单个对象/属性,如下所示:

 [{"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"}....]

我想使用以下格式的正确元素标签将此对象转换为XML:

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

我找到了一段代码来转换对象:

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;
    }

这肯定会在某种程度上转换对象,但是,它会尝试为每个属性集创建一个键,并将这些属性连接为一个字符串。

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

关于如何使用此功能正确描述XML格式的任何建议?

1 个答案:

答案 0 :(得分:1)

您可以使用字符串模板来做到这一点

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))