sai v sai v - 1 year ago 115
Javascript Question

convert json string to xml string in javascript

I got a json string as a result of ajax request.
And I need to convert json into xml string using javascript/jquery.
Please help me.
Json string like below:

var json =
"{
"Data": {
"SOM": {
"Tab": [
{
"Values": {
"SelectedValues": null,
"LoadedValues": null,
"ExpandedValues": null,
"ID": "msorgrole"
},
"ID": "OrgRole"
},
{
"Values": {
"SelectedValues": null,
"LoadedValues": null,
"ExpandedValues": null,
"ID": "msorg"
},
"ID": "Organization"
},
{
"Values": {
"SelectedValues": null,
"LoadedValues": null,
"ExpandedValues": null,
"ID": "mscontenttype"
},
"ID": "PeopleType"
},
{
"Values": {
"SelectedValues": ",B79720D5-0E95-4CB7-B4F9-37BE24696F4F,831A2A77-B758-493A-B0F4-991A6427C31C,",
"LoadedValues": null,
"ExpandedValues": null,
"ID": "mspeople"
},
"ID": "People"
}
]
}
}
}"


I need to convert the above json string like below:

var json = "<Data><SOM><Tab ID="OrgRole"> <Values ID="msorgrole"><SelectedValues /> <LoadedValues /> <ExpandedValues /></Values></Tab><Tab ID="Organization"> <Values ID="msorg"><SelectedValues /> <LoadedValues /> <ExpandedValues /></Values></Tab><Tab ID="PeopleType"> <Values ID="mscontenttype"><SelectedValues /> <LoadedValues /> <ExpandedValues /></Values></Tab><Tab ID="People"> <Values ID="mspeople"><SelectedValues>,831A2A77-B758-493A-B0F4-991A6427C31C,B79720D5-0E95-4CB7-B4F9-37BE24696F4F,</SelectedValues> <LoadedValues /> <ExpandedValues /></Values></Tab></SOM></Data>"

Answer Source

You can use http://goessner.net/download/prj/jsonxml/ like this using the function json2xml:

var data = '{"Data":{"SOM":{"Tab":[{"Values":{"SelectedValues":null,"LoadedValues":null,"ExpandedValues":null,"ID":"msorgrole"},"ID":"OrgRole"},{"Values":{"SelectedValues":null,"LoadedValues":null,"ExpandedValues":null,"ID":"msorg"},"ID":"Organization"},{"Values":{"SelectedValues":null,"LoadedValues":null,"ExpandedValues":null,"ID":"mscontenttype"},"ID":"PeopleType"},{"Values":{"SelectedValues":",B79720D5-0E95-4CB7-B4F9-37BE24696F4F,831A2A77-B758-493A-B0F4-991A6427C31C,","LoadedValues":null,"ExpandedValues":null,"ID":"mspeople"},"ID":"People"}]}}}';

var jsonObj = JSON.parse(data); // important to first convert json string into object

alert(json2xml(jsonObj));
<script src="http://goessner.net/download/prj/jsonxml/json2xml.js"></script>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download