README
simpleconvert-xml
(c)Bumblehead, 2013,2014,2015,2016 MIT-license
Performs javascript and xml conversions in a browser or node.js environment (with xmldom). xml to json conversions can be messy. See below for details.
var xmlnode = new DOMParser().parseFromString([
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>",
"<data>",
" <price>$15.98</price>",
" <happy>",
" <say>I'm happy</say>",
" <respond>you're happy</respond>",
" <conclude>we're all happy</conclude>",
" </happy>",
" <isFinal>true</isFinal>",
" <name>dave</name>",
" <name>chris</name>",
" <fooArr>value</fooArr>",
"</data>"
].join('\n'), 'text/xml');
simpleconvertxml.getXMLAsObj(xmlnode);
//{
// "data": {
// "price": "$15.98",
// "happy": {
// "say": "I'm happy",
// "respond": "you're happy",
// "conclude": "we're all happy"
// },
// "isFinal": "true",
// "name": [
// "dave",
// "chris"
// ],
// "fooArr": [
// "value"
// ]
// }
//}
simpleconvertxml.getObjAsXMLstr(
simpleconvertxml.getXMLAsObj(xmlnode)
);
//<?xml version="1.0" encoding="UTF-8"?>
//<data>
//<price>$15.98</price>
//<happy>
//<say>I'm happy</say>
//<respond>you're happy</respond>
//<conclude>we're all happy</conclude>
//</happy>
//<isFinal>true</isFinal>
//<name>dave</name>
//<name>chris</name>
//<fooArr>value</fooArr>
//</data>
conversion issues
XML has no array. Any xml element can have multiple childs or a single one. A simple parser maps single nodes as an object value and multiple nodes as an array.
If you control the source of the xml, you may flag the presence of an array by using node names affixed with
Arr
, for examplefooArr
(see above).var xmlnode_currencies = new DOMParser().parseFromString([ '<currencies>', ' <currency type="GNS">', ' <displayName>syli guineano</displayName>', ' </currency>', ' <currency type="GNB">', ' <displayName>ekuele de Guinea Ecuatorial</displayName>', ' <displayName>other</displayName>', ' </currency>', '</currencies>' ].join('\n'), 'text/xml'); simpleconvertxml.getXMLAsObj(xmlnode_currencies); //{ // "currencies": { // "currency": [ // { // "displayName": "syli guineano", // "type": "GNS" // }, // { // "displayName": [ // "ekuele de Guinea Ecuatorial", // "other" // ], // "type": "GNB" // } // ] // } //}
multiple node attributes result in multiple property definitions.
var xmlnode_types = new DOMParser().parseFromString([ '<types>', ' <type type="big5han" key="collation">', ' orden del chino tradicional - Big5', ' </type>', ' <type type="buddhist" key="calendar">', ' calendario budista', ' </type>', '</types>' ].join('\n'), 'text/xml'); simpleconvertxml.getXMLAsObj(xmlnode_types); //{ // "types": { // "type": [ // { // "collation": "orden del chino tradicional - Big5", // "big5han": "orden del chino tradicional - Big5" // }, // { // "calendar": "calendario budista", // "buddhist": "calendario budista" // } // ] // } //}
Some xml nodes have no node value.
var xmlnode_identity = new DOMParser().parseFromString([ '<identity>', ' <version number="$Revision: 1.128