我是java脚本的新手。
现有的javascript代码可以读取JSON文档并创建XML。但是xml文档没有与JSON文档中的元素顺序相同的元素。 如何实现这一目标?目前,java脚本使用树。我使用list,hash但是徒劳无功。 不确定要使用哪种javascript数据结构,以便不按排序顺序/字母顺序存储数据。 任何代码示例都非常受欢迎。
JSON:
{
"data:xxData": {
"xyz": "value",
"abc": "order",
}
}
结果XML:
<data:xxData>
<abc>order</abc>
<xyz>value</xyz>
</data:xxData>
预期的正确XML:
<data:xxData>
<xyz>value</xyz>
<abc>order</abc>
</data:xxData>
提前致谢。
以下是代码:
我通过传递JSON字符串来调用writeXML。
XML.ObjTree.prototype.writeXML = function ( tree ) {
var xml = this.hash_to_xml( null, tree );
return this.xmlDecl + xml;
};
XML.ObjTree.prototype.hash_to_xml = function ( name, tree ) {
var elem = [];
var attr = [];
for( var key in tree ) {
print("key: "+ key+'\n')
//print("tree: "+ tree[key]+'\n')
if ( ! tree.hasOwnProperty(key) ) continue;
var val = tree[key];
if ( key.charAt(0) != this.attr_prefix ) {
if ( typeof(val) == "undefined" || val == null ) {
elem[elem.length] = "<"+key+" />";
} else if ( typeof(val) == "object" && val.constructor == Array ) {
elem[elem.length] = this.array_to_xml( key, val );
} else if ( typeof(val) == "object" ) {
elem[elem.length] = this.hash_to_xml( key, val );
} else {
elem[elem.length] = this.scalar_to_xml( key, val );
}
} else {
attr[attr.length] = " "+(key.substring(1))+'="'+(this.xml_escape( val ))+'"';
}
}
var jattr = attr.join("");
var jelem = elem.join("");
if ( typeof(name) == "undefined" || name == null ) {
// no tag
} else if ( elem.length > 0 ) {
if ( jelem.match( /\n/ )) {
jelem = "<"+name+jattr+">\n"+jelem+"</"+name+">\n";
} else {
jelem = "<"+name+jattr+">" +jelem+"</"+name+">\n";
}
} else {
jelem = "<"+name+jattr+" />\n";
}
return jelem;
};
XML.ObjTree.prototype.array_to_xml = function ( name, array ) {
var out = [];
for( var i=0; i<array.length; i++ ) {
var val = array[i];
if ( typeof(val) == "undefined" || val == null ) {
out[out.length] = "<"+name+" />";
} else if ( typeof(val) == "object" && val.constructor == Array ) {
out[out.length] = this.array_to_xml( name, val );
} else if ( typeof(val) == "object" ) {
out[out.length] = this.hash_to_xml( name, val );
} else {
out[out.length] = this.scalar_to_xml( name, val );
}
}
return out.join("");
};
// method: scalar_to_xml( tagName, text )
XML.ObjTree.prototype.scalar_to_xml = function ( name, text ) {
if ( name == "#text" ) {
return this.xml_escape(text);
} else {
return "<"+name+">"+this.xml_escape(text)+"</"+name+">\n";
}
};
// method: xml_escape( text )
XML.ObjTree.prototype.xml_escape = function ( text ) {
return (text + '').replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/"/g,'"');
};
答案 0 :(得分:0)
你走了:
JSON:
{
"data:xxData": [
{ "xyz": "value" },
{ "abc": "order" }
]
}
}