我想将此字符串转换为xml格式。
在此之前,似乎我需要将这个'字符串'放在'对象'中并将其转换为'JSON格式'。 (我认为)
我的字符串是
"oTest^A1^BB:a1bb,oTest^A2^BB:a1cc,oTest^A1^CC:a2bb,oTest^A2^CC:a2cc"
JSON格式是
{
"oTest": {
"A1": {
"BB": "a1bb",
"CC": "a1cc"
},
"A2": {
"BB": "a2bb",
"CC": "a2cc"
}
}
}
最后我想要
<oTest>
<A1>
<BB>a1bb</BB>
<CC>a1cc</CC>
</A1>
<A2>
<BB>a2bb</BB>
<CC>a2cc</CC>
</A2>
</oTest>
这个XML格式字符串。
(是否可以直接转换为XML而无需转换为JSON?)
我试图将我的字符串放入'对象'并且未能获得重复值。
请ECMAscript 5版..
我试过这个
function fn_str2obj2Json(sStr)
{
var objChild1 = {};
var objChild2 = {};
var objRtn = {};
var sStr = "oTest^A1^BB:a1bb,oTest^A2^BB:a1cc,oTest^A1^CC:a2bb,oTest^A2^CC:a2cc";
var arrStr = sStr.split(',');
for (var i = 0; i < arrStr.length; i++) {
var arrSpe = arrStr[i].split('^');
var sLineName = arrSpe[0];
var sTankName = arrSpe[1];
var sItemName = arrSpe[2].split(':')[0];
var sValue = arrSpe[2].split(':')[1];
objChild2["" + sItemName + ""] = sValue;
objChild1["" + sTankName + ""] = objChild2;
objRtn["" + sLineName + ""] = objChild1;
//$.extend(objChild1, objChild2);
//objChild1 = {};
//objChild2 = {};
}
var sJsonVal = JSON.stringify(objRtn, null, 2);
//var sXmlVal = x2js.json2xml_str($.parseJSON(sJsonVal));
objRtn = {};
}
答案 0 :(得分:0)
{
var s = "oTest^A1^BB:a1bb,oTest^A2^BB:a1cc,oTest^A1^CC:a2bb,oTest^A2^CC:a2cc";
var data = {};
s.split(",").forEach(function (ele) {
var key_val = ele.split(":");
var key = key_val[0];
var val = key_val[1];
var sub_keys = key.split("^");
var last_subkey = sub_keys.pop();
var p = data;
sub_keys.forEach(function (subkey) {
if (!p[subkey])
p[subkey] = {};
p = p[subkey];
});
p[last_subkey] = val;
});
var root_ele_name = Object.keys(data)[0];
// The rest of this program assumes this program is run in a browser.
var doc = document.implementation.createDocument(null, root_ele_name);
var creator = function (creator, doc, parent, p) {
if (typeof(p) === 'object') {
for (ele_name in p) {
var node = doc.createElement(ele_name);
parent.appendChild(node);
creator(creator, doc, node, p[ele_name]);
}
} else {
var node = document.createTextNode(p);
parent.appendChild(node);
}
};
creator(creator, doc, doc.documentElement, data[root_ele_name]);
var xml = new XMLSerializer().serializeToString(doc);
alert(xml);
}