JXON

  • Revision slug: JXON
  • Revision title: JXON
  • Revision id: 6530
  • Created:
  • Creator: fusionchess
  • Is current revision? No
  • Comment Conversion snippets: introduction; 50 words added, 13 words removed

Revision Content

JXON (lossless Javascript XML Object Notation) is a generic name by which is defined the representation of Javascript Objects using XML. There are not real standards for this conversion, but some conventions begin to appear on the web. There are some cases in which the whole content of an XML document must be readed from the JavaScript interpreter (like for web-apps languages or settings XML documents, for example). In these cases JXON could represent the most practical way.

Note: If you are interested to address only some parts of an XML document, use XPath instead of converting the whole document into JSON!

In this article we will see how to convert a parsed XML document (i.e. an instance of Document) to a JavaScript Object tree (i.e. a tree of nested instances of Object) and viceversa with some different algorithms.

If you want a complete bidirectional JXON library (modelled on the JSON global object), skip to the dedicated paragraph.

Conversion snippets

Now imagine to have this sample XML document:

example.xml
<?xml version="1.0"?>
<!DOCTYPE catalog SYSTEM "catalog.dtd">
<catalog>
  <product description="Cardigan Sweater">
    <catalog_item gender="Men's">
      <item_number>QWZ5671</item_number>
      <price>39.95</price>
      <size description="Medium">
        <color_swatch image="red_cardigan.jpg">Red</color_swatch>
        <color_swatch image="burgundy_cardigan.jpg">Burgundy</color_swatch>
      </size>
      <size description="Large">
        <color_swatch image="red_cardigan.jpg">Red</color_swatch>
        <color_swatch image="burgundy_cardigan.jpg">Burgundy</color_swatch>
      </size>
    </catalog_item>
    <catalog_item gender="Women's">
      <item_number>RRX9856</item_number>
      <discount_until>Dec 25, 1995</discount_until>
      <price>42.50</price>
      <size description="Medium">
        <color_swatch image="black_cardigan.jpg">Black</color_swatch>
      </size>
    </catalog_item>
  </product>
  <script type="text/javascript"><![CDATA[function matchwo(a,b) {
    if (a < b && a < 0) { return 1; }
    else { return 0; }
}]]></script>
</catalog>

First, create a DOM tree like the previous example as described in the How to Create a DOM tree article. If you have already have a DOM tree from using XMLHttpRequest, skip to the next paragraph.

The algorithms proposed here (see: #1, #2, #3, #4) will consider only the following types of nodes and their attributes:

  1. Document (only as function argument),
  2. DocumentFragment (only as function argument),
  3. Element,
  4. Text (never as function argument),
  5. CDATASection (never as function argument).

It is a good and standardized compromise for a Javascript usage, since all of the information of an XML Document is contained in this types of nodes. All other informations (like processing instructions, schemas, comments, etc.) will be lost (but due to the nature of the information which is lost, this type of algorithms is considered however lossless, since what is lost is meta-information and not information).

In order to avoid conflicts, the representation of nodes and attributes names is case insensitive (always rendered in lower case), so object's local properties names setted via JavaScript must always have some kind of capitalization (initial, internal, etc.), as you can see below. Following algorithms are sketchily based on the Parker convention, version 0.4 (which prescribes the transformation of tags names into object properties names and the recognition of the typeof of each Node's nodeValue property), but with some differences. Moreover, all algorithms are equally lossless for the contemplated nodes.

Now let's serialize doc — the DOM tree — to a Javascript Object Tree (you can read more about working with Objects and how Javascript is Object-Oriented). We can use several algorithms to convert its content to a Javascript Object Tree.

Algorithm #1: a verbose way

This simple recursive constructor will convert an XML DOM tree to a JavaScript Object tree. The text content of each element is stored into the keyValue property, while nodeAttributes, if exist, are listed under the child object keyAttributes. The constructor's argument can be the entire XML Document, a DocumentFragment or simply an Element node of it.

function parseText (sValue) {
  if (/^\s*$/.test(sValue)) { return null; }
  if (/^(?:true|false)$/i.test(sValue)) { return sValue.toLowerCase() === "true"; }
  if (isFinite(sValue)) { return parseFloat(sValue); }
  if (isFinite(Date.parse(sValue))) { return new Date(sValue); }
  return sValue;
}

function JXONData (oXMLParent) {
  var nAttrLen = 0, nLength = 0, sCollectedTxt = "";
  if (oXMLParent.hasChildNodes()) {
    for (var oNode, sProp, vContent, nItem = 0; nItem < oXMLParent.childNodes.length; nItem++) {
      oNode = oXMLParent.childNodes.item(nItem);
      if ((oNode.nodeType - 1 | 1) === 3) { sCollectedTxt += oNode.nodeType === 3 ? oNode.nodeValue.trim() : oNode.nodeValue; } // nodeType is "Text" (3) or "CDATASection" (4)
      else if (oNode.nodeType === 1 && !oNode.prefix) { // nodeType is "Element" (1)
        sProp = oNode.nodeName.toLowerCase();
        vContent = new JXONData(oNode);
        if (this.hasOwnProperty(sProp)) {
          if (this[sProp].constructor !== Array) { this[sProp] = [this[sProp]]; }
          this[sProp].push(vContent);
        } else { this[sProp] = vContent; nLength++; }
      }
    }
    this.keyValue = parseText(sCollectedTxt);
  } else { this.keyValue = null; }
  if (oXMLParent.hasAttributes()) {
    var oAttrib;
    this.keyAttributes = {};
    for (nAttrLen; nAttrLen < oXMLParent.attributes.length; nAttrLen++) {
      oAttrib = oXMLParent.attributes.item(nAttrLen);
      this.keyAttributes[oAttrib.nodeName.toLowerCase()] = parseText(oAttrib.nodeValue.trim());
    }
  }
  // optional properties and methods; you could safely adjoust/remove them...
  this.keyLength = nLength;
  this.attributesLength = nAttrLen;
  // this.DOMNode = oXMLParent;
  this.valueOf = function () { return this.keyValue; };
  this.toString = function () { return String(this.keyValue); };
  this.getItem = function (nChildId) {
    if (nLength === 0) { return null; }
    var nCount = 0;
    for (var sKey in this) { if (nCount === nChildId) { return this[sKey]; } nCount++; }
    return null;
  };
  this.getAttribute = function (nAttrId) {
    if (nAttrLen === 0 || nAttrId + 1 > nAttrLen) { return null; }
    var nAttr = 0;
    for (var sAttrName in this.keyAttributes) { if (nAttr === nAttrId) { return this.keyAttributes[sAttrName]; } nAttr++; }
    return null;
  };
  this.hasChildren = function () { return this.keyLength > 0; };

  /* Object.freeze(this); */
}

var myObject = new JXONData(doc);
// we got our javascript object! try: alert(JSON.stringify(myObject));
Note: If you want to freeze the whole object tree (because of the "static" nature of a XML document), uncomment the string: /* Object.freeze(this); */. The Object.freeze method prevents new properties from being added to it, prevents existing properties from being removed and prevents existing properties, or their enumerability, configurability, or writability, from being changed. In essence the object tree is made effectively immutable.

With this algorithm our example will become:

{
  "catalog": {
    "product": {
      "catalog_item": [{
        "item_number": {
          "keyValue": "QWZ5671",
          "keyLength": 0,
          "attributesLength": 0
        },
        "price": {
          "keyValue": 39.95,
          "keyLength": 0,
          "attributesLength": 0
        },
        "size": [{
          "color_swatch": [{
            "keyValue": "Red",
            "keyAttributes": {
              "image": "red_cardigan.jpg"
            },
            "keyLength": 0,
            "attributesLength": 1
          }, {
            "keyValue": "Burgundy",
            "keyAttributes": {
              "image": "burgundy_cardigan.jpg"
            },
            "keyLength": 0,
            "attributesLength": 1
          }],
          "keyValue": null,
          "keyAttributes": {
            "description": "Medium"
          },
          "keyLength": 1,
          "attributesLength": 1
        }, {
          "color_swatch": [{
            "keyValue": "Red",
            "keyAttributes": {
              "image": "red_cardigan.jpg"
            },
            "keyLength": 0,
            "attributesLength": 1
          }, {
            "keyValue": "Burgundy",
            "keyAttributes": {
              "image": "burgundy_cardigan.jpg"
            },
            "keyLength": 0,
            "attributesLength": 1
          }],
          "keyValue": null,
          "keyAttributes": {
            "description": "Large"
          },
          "keyLength": 1,
          "attributesLength": 1
        }],
        "keyValue": null,
        "keyAttributes": {
          "gender": "Men's"
        },
        "keyLength": 3,
        "attributesLength": 1
      }, {
        "item_number": {
          "keyValue": "RRX9856",
          "keyLength": 0,
          "attributesLength": 0
        },
        "discount_until": {
          "keyValue": new Date(1995, 11, 25),
          "keyLength": 0,
          "attributesLength": 0
        },
        "price": {
          "keyValue": 42.5,
          "keyLength": 0,
          "attributesLength": 0
        },
        "size": {
          "color_swatch": {
            "keyValue": "Black",
            "keyAttributes": {
              "image": "black_cardigan.jpg"
            },
            "keyLength": 0,
            "attributesLength": 1
          },
          "keyValue": null,
          "keyAttributes": {
            "description": "Medium"
          },
          "keyLength": 1,
          "attributesLength": 1
        },
        "keyValue": null,
        "keyAttributes": {
          "gender": "Women's"
        },
        "keyLength": 4,
        "attributesLength": 1
      }],
      "keyValue": null,
      "keyAttributes": {
        "description": "Cardigan Sweater"
      },
      "keyLength": 1,
      "attributesLength": 1
    },
    "script": {
      "keyValue": "function matchwo(a,b) {\n  if (a < b && a < 0) { return 1; }\n  else { return 0; }\n}",
      "keyAttributes": {
        "type": "text/javascript"
      },
      "keyLength": 0,
      "attributesLength": 1
    },
    "keyValue": null,
    "keyLength": 2,
    "attributesLength": 0
  },
  "keyValue": null,
  "keyLength": 1,
  "attributesLength": 0
}

It is a recommanded way if you don't know the structure of the XML document.

Algorithm #2: a less verbose way

Here is another, simpler, conversion method, where nodeAttributes are listed under the same object of children nodes, but have the “@” prefix. As above, the text content is stored into the keyValue property. The constructor's argument can be the entire XML Document, a DocumentFragment or simply an Element node of it.

function parseText (sValue) {
  if (/^\s*$/.test(sValue)) { return null; }
  if (/^(?:true|false)$/i.test(sValue)) { return sValue.toLowerCase() === "true"; }
  if (isFinite(sValue)) { return parseFloat(sValue); }
  if (isFinite(Date.parse(sValue))) { return new Date(sValue); }
  return sValue;
}

function JXONData (oXMLParent) {
  if (oXMLParent.hasChildNodes()) {
    var sCollectedTxt = "";
    for (var oNode, sProp, vContent, nItem = 0; nItem < oXMLParent.childNodes.length; nItem++) {
      oNode = oXMLParent.childNodes.item(nItem);
      if ((oNode.nodeType - 1 | 1) === 3) { sCollectedTxt += oNode.nodeType === 3 ? oNode.nodeValue.trim() : oNode.nodeValue; }
      else if (oNode.nodeType === 1 && !oNode.prefix) {
        sProp = oNode.nodeName.toLowerCase();
        vContent = new JXONData(oNode);
        if (this.hasOwnProperty(sProp)) {
          if (this[sProp].constructor !== Array) { this[sProp] = [this[sProp]]; }
          this[sProp].push(vContent);
        } else { this[sProp] = vContent; }
      }
    }
    if (sCollectedTxt) { this.keyValue = parseText(sCollectedTxt); }
  }
  if (oXMLParent.hasAttributes()) {
    var oAttrib;
    for (var nAttrib = 0; nAttrib < oXMLParent.attributes.length; nAttrib++) {
      oAttrib = oXMLParent.attributes.item(nAttrib);
      this["@" + oAttrib.nodeName.toLowerCase()] = parseText(oAttrib.nodeValue.trim());
    }
  }
  /* Object.freeze(this); */
}

var myObject = new JXONData(doc);
// we got our javascript object! try: alert(JSON.stringify(myObject));
Note: If you want to freeze the whole object tree (because of the "static" nature of a XML document), uncomment the string: /* Object.freeze(this); */. The Object.freeze method prevents new properties from being added to it, prevents existing properties from being removed and prevents existing properties, or their enumerability, configurability, or writability, from being changed. In essence the object tree is made effectively immutable.

With this algorithm our example will become:

{
  "catalog": {
    "product": {
      "catalog_item": [{
        "item_number": {
          "keyValue": "QWZ5671"
        },
        "price": {
          "keyValue": 39.95
        },
        "size": [{
          "color_swatch": [{
            "keyValue": "Red",
            "@image": "red_cardigan.jpg"
          }, {
            "keyValue": "Burgundy",
            "@image": "burgundy_cardigan.jpg"
          }],
          "@description": "Medium"
        }, {
          "color_swatch": [{
            "keyValue": "Red",
            "@image": "red_cardigan.jpg"
          }, {
            "keyValue": "Burgundy",
            "@image": "burgundy_cardigan.jpg"
          }],
          "@description": "Large"
        }],
        "@gender": "Men's"
      }, {
        "item_number": {
          "keyValue": "RRX9856"
        },
        "discount_until": {
          "keyValue": new Date(1995, 11, 25)
        },
        "price": {
          "keyValue": 42.5
        },
        "size": {
          "color_swatch": {
            "keyValue": "Black",
            "@image": "black_cardigan.jpg"
          },
          "@description": "Medium"
        },
        "@gender": "Women's"
      }],
      "@description": "Cardigan Sweater"
    },
    "script": {
      "keyValue": "function matchwo(a,b) {\n  if (a < b && a < 0) { return 1; }\n  else { return 0; }\n}",
      "@type": "text/javascript"
    }
  }
}

It is a possible way if you partially know the structure of the XML document.

Algorithm #3: a synthetic way

Here is another method of conversion. This algorithm is the closest to the Parker convention. It is very similar to the previous one, except that nodes which do not contain other recognizable nodes than Text or CDATASection are not treated as objects, but directly as booleans, strings, numbers or Date objects (see the Parker convention). Empty nodes (i.e. which do not contain other Element nodes, Text nodes or CDATASection nodes) have the default value true (see the Code considerations). Also, this time it is not used a constructor, but a function. The function's argument can be the entire XML Document, a DocumentFragment or simply an Element node of it. In many cases this one represents the most practical conversion method.

function parseText (sValue) {
  if (/^\s*$/.test(sValue)) { return null; }
  if (/^(?:true|false)$/i.test(sValue)) { return sValue.toLowerCase() === "true"; }
  if (isFinite(sValue)) { return parseFloat(sValue); }
  if (isFinite(Date.parse(sValue))) { return new Date(sValue); }
  return sValue;
}

function getJXONData (oXMLParent) {
  var vResult = /* put here the default value for empty nodes! */ true, nLength = 0, sCollectedTxt = "";
  if (oXMLParent.hasAttributes()) {
    vResult = {};
    for (nLength; nLength < oXMLParent.attributes.length; nLength++) {
      oAttrib = oXMLParent.attributes.item(nLength);
      vResult["@" + oAttrib.nodeName.toLowerCase()] = parseText(oAttrib.nodeValue.trim());
    }
  }
  if (oXMLParent.hasChildNodes()) {
    for (var oNode, sProp, vContent, nItem = 0; nItem < oXMLParent.childNodes.length; nItem++) {
      oNode = oXMLParent.childNodes.item(nItem);
      if (oNode.nodeType === 4) { sCollectedTxt += oNode.nodeValue; } /* nodeType is "CDATASection" (4) */
      else if (oNode.nodeType === 3) { sCollectedTxt += oNode.nodeValue.trim(); } /* nodeType is "Text" (3) */
      else if (oNode.nodeType === 1 && !oNode.prefix) { /* nodeType is "Element" (1) */
        if (nLength === 0) { vResult = {}; }
        sProp = oNode.nodeName.toLowerCase();
        vContent = getJXONData(oNode);
        if (vResult.hasOwnProperty(sProp)) {
          if (vResult[sProp].constructor !== Array) { vResult[sProp] = [vResult[sProp]]; }
          vResult[sProp].push(vContent);
        } else { vResult[sProp] = vContent; nLength++; }
      }
    }
  }
  if (sCollectedTxt) { nLength > 0 ? vResult.keyValue = parseText(sCollectedTxt) : vResult = parseText(sCollectedTxt); }
  /* if (nLength > 0) { Object.freeze(vResult); } */
  return vResult;
}

var myObject = getJXONData(doc);
// we got our javascript object! try: alert(JSON.stringify(myObject));
Note: If you want to freeze the whole object tree (because of the "static" nature of a XML document), uncomment the string: /* if (nLength > 0) { Object.freeze(vResult); } */. The Object.freeze method prevents new properties from being added to it, prevents existing properties from being removed and prevents existing properties, or their enumerability, configurability, or writability, from being changed. In essence the object tree is made effectively immutable.

With this algorithm our example will become:

{
  "catalog": {
    "product": {
      "@description": "Cardigan Sweater",
      "catalog_item": [{
        "@gender": "Men's",
        "item_number": "QWZ5671",
        "price": 39.95,
        "size": [{
          "@description": "Medium",
          "color_swatch": [{
            "@image": "red_cardigan.jpg",
            "keyValue": "Red"
          }, {
            "@image": "burgundy_cardigan.jpg",
            "keyValue": "Burgundy"
          }]
        }, {
          "@description": "Large",
          "color_swatch": [{
            "@image": "red_cardigan.jpg",
            "keyValue": "Red"
          }, {
            "@image": "burgundy_cardigan.jpg",
            "keyValue": "Burgundy"
          }]
        }]
      }, {
        "@gender": "Women's",
        "item_number": "RRX9856",
        "discount_until": new Date(1995, 11, 25),
        "price": 42.5,
        "size": {
          "@description": "Medium",
          "color_swatch": {
            "@image": "black_cardigan.jpg",
            "keyValue": "Black"
          }
        }
      }]
    },
    "script": {
      "@type": "text/javascript",
      "keyValue": "function matchwo(a,b) {\n  if (a < b && a < 0) { return 1; }\n  else { return 0; }\n}"
    }
  }
}

It is a recommanded way if you know the structure of the XML document.

Algorithm #4: a very minimalist way

The following is another possible way of conversion. It is very close to the Parker convention, too. With this algorithm all Element nodes which contain other child Element nodes and Text or CDATASection nodes in the same level are treated as instances of Boolean, Number, String, or Date Constructors. So any child Element node, if exists, will be nested in these types of objects.

For example:

<employee type="usher">John Smith</employee>
<manager>Lisa Carlucci</manager>

will become

var myObject = {
  "employee": new String("John Smith"),
  "manager": "Lisa Carlucci"
};

myObject.employee["@type"] = "usher";

// test

alert(myObject.manager); // "Lisa Carlucci"
alert(myObject.employee["@type"]); // "usher"
alert(myObject.employee); // "John Smith"
Note: This algorithm represents a special case of conversion. The generated JavaScript Object tree is not stringifyable (see the Code considerations). It is very practical for internal JavaScript access, but don't use it if you want to transfer the tree via JSON string!

As for the third algorithm, nodes which do not contain other recognizable nodes than Text or CDATASection are not treated as objects, but directly as booleans, strings, numbers (primitive values) or Date objects; and empty nodes (i.e. which do not contain other Element nodes, Text nodes or CDATASection nodes) have the default value true. As for the third algorithm it is not used a constructor, but a function. The function's argument can be the entire XML Document, a DocumentFragment or simply an Element node of it.

function parseText (sValue) {
  if (/^\s*$/.test(sValue)) { return null; }
  if (/^(?:true|false)$/i.test(sValue)) { return sValue.toLowerCase() === "true"; }
  if (isFinite(sValue)) { return parseFloat(sValue); }
  if (isFinite(Date.parse(sValue))) { return new Date(sValue); }
  return sValue;
}

function objectify (vValue) {
  if (vValue === null) {
    return new (function() {
      this.toString = function() { return "null"; }
      this.valueOf = function() { return null; }
    })();
  }
  return vValue instanceof Object ? vValue : new vValue.constructor(vValue);
}

var aTmpEls = []; // loaded element nodes cache

function getJXONData (oXMLParent) {
  var  sProp, vContent, vResult, nLength = 0, nLevelStart = aTmpEls.length,
       nChildren = oXMLParent.hasChildNodes() ? oXMLParent.childNodes.length : 0, sCollectedTxt = "";

  for (var oNode, nItem = 0; nItem < nChildren; nItem++) {
    oNode = oXMLParent.childNodes.item(nItem);
    if (oNode.nodeType === 4) { sCollectedTxt += oNode.nodeValue; } /* nodeType is "CDATASection" (4) */
    else if (oNode.nodeType === 3) { sCollectedTxt += oNode.nodeValue.trim(); } /* nodeType is "Text" (3) */
    else if (oNode.nodeType === 1 && !oNode.prefix) { aTmpEls.push(oNode); } /* nodeType is "Element" (1) */
  }

  var nLevelEnd = aTmpEls.length, vBuiltVal = parseText(sCollectedTxt);

  if (oXMLParent.hasAttributes()) {
    vResult = objectify(vBuiltVal);
    for (nLength; nLength < oXMLParent.attributes.length; nLength++) {
      oAttrib = oXMLParent.attributes.item(nLength);
      vResult["@" + oAttrib.nodeName.toLowerCase()] = parseText(oAttrib.nodeValue.trim());
    }
  } else if (nLevelEnd > nLevelStart) { vResult = objectify(vBuiltVal); }

  for (var nElId = nLevelStart; nElId < nLevelEnd; nElId++) {
    sProp = aTmpEls[nElId].nodeName.toLowerCase();
    vContent = getJXONData(aTmpEls[nElId]);
    if (vResult.hasOwnProperty(sProp)) {
    if (vResult[sProp].constructor !== Array) { vResult[sProp] = [vResult[sProp]]; }
      vResult[sProp].push(vContent);
    } else { vResult[sProp] = vContent; nLength++; }
  }

  aTmpEls.length = nLevelStart;

  if (nLength === 0) { vResult = sCollectedTxt ? vBuiltVal : /* put here the default value for empty nodes: */ true; }
  /* else { Object.freeze(vResult); } */

  return vResult;
}

var myObject = getJXONData(doc);
alert(myObject.catalog.product.catalog_item[1].size.color_swatch["@image"]); // "black_cardigan.jpg"
alert(myObject.catalog.product.catalog_item[1].size.color_swatch); // "Black" !
Note: If you want to freeze the whole object tree (because of the "static" nature of a XML document), uncomment the string: /* else { Object.freeze(vResult); } */. The Object.freeze method prevents new properties from being added to it, prevents existing properties from being removed and prevents existing properties, or their enumerability, configurability, or writability, from being changed. In essence the object tree is made effectively immutable.

It is a possible way if you know the structure of the XML document.

Reverse Algorithms

It is possible to reverse the algorithms proposed here in order to build a new XML document starting from a JavaScript Objects Tree. For simplicity, we will propose here a single example, which in a unique code represents the inversion of all our algorithms.

function createXML (oJSONData) {
  function loadObjTree (oParentEl, oParentObj) {
    var vValue, oChild;
    if (oParentObj instanceof String || oParentObj instanceof Number || oParentObj instanceof Boolean) {
      oParentEl.appendChild(oNewDoc.createTextNode(oParentObj.toString())); /* verbosity level is 0 */
    } else if (oParentObj.constructor === Date) {
      oParentEl.appendChild(oNewDoc.createTextNode(oParentObj.toGMTString()));    
    }
    for (var sName in oParentObj) {
      if (isFinite(sName)) { continue; } /* verbosity level is 0 */
      vValue = oParentObj[sName];
      if (sName === "keyValue") {
        if (vValue !== null && vValue !== true) { oParentEl.appendChild(oNewDoc.createTextNode(vValue.constructor === Date ? vValue.toGMTString() : String(vValue))); }
      } else if (sName === "keyAttributes") { /* verbosity level is 3 */
        for (var sAttrib in vValue) { oParentEl.setAttribute(sAttrib, vValue[sAttrib]); }
      } else if (sName.charAt(0) === "@") {
        oParentEl.setAttribute(sName.slice(1), vValue);
      } else if (vValue.constructor === Array) {
        for (var nItem = 0; nItem < vValue.length; nItem++) {
          oChild = oNewDoc.createElement(sName);
          loadObjTree(oChild, vValue[nItem]);
          oParentEl.appendChild(oChild);
        }
      } else {
        oChild = oNewDoc.createElement(sName);
        if (vValue instanceof Object) {
          loadObjTree(oChild, vValue);
        } else if (vValue !== null && vValue !== true) {
          oChild.appendChild(oNewDoc.createTextNode(vValue.toString()));
        }
        oParentEl.appendChild(oChild);
      }
    }
  }
  const oNewDoc = document.implementation.createDocument("", "", null);
  loadObjTree(oNewDoc, oJSONData);
  return oNewDoc;
}

var newDoc = createXML(myObject);
// we got our Document instance! try: alert((new XMLSerializer()).serializeToString(newDoc));
Note: With this code the Date instances, if exist, will be converted into Strings through the toGMTString() method. Nothing prohibits the use of any other conversion method. In addition, all properties of the tree with a true value will be converted into empty elements with no text nodes (see the Code considerations).

It is a good solution if you want to automate the creation of an XML document. It is a bad choice, instead, if you want to re-build an XML document previously converted into JSON. Although the conversion is very faithful (except for CDATASection nodes , which will be converted into Text nodes), the process is unnecessarily costly. In fact, if our goal is to edit an XML document, it is strongly recommended to work on it rather than create new ones.

The Parker Convention

The functions listed above for the conversion of an XML document to JSON (often called «JXON algorithms») are more or less freely based on the Parker Convention. It is called “Parker Convention” in opposition to “BadgerFish Convention”, after the comic Parker & Badger by Cuadrado. See also: BadgerFish Convention.

The following is a transcription of the Parker Convention paper (version 0.4), from the page “TransformingRules” of the xml2json-xslt project site.

This Convention was written in order to regulate the conversion to JSON from XSLT, so parts of it are futile for Javascript.

Translation JSON

  1. The root element will be absorbed, for there is only one:

    <root>test</root>

    becomes

    "test"
    
  2. Element names become object properties:

    <root><name>Xml</name><encoding>ASCII</encoding></root>

    becomes

    {
      "name": "Xml",
      "encoding": "ASCII"
    }
    
  3. Numbers are recognized (integers and decimals):

    <root><age>12</age><height>1.73</height></root>

    becomes

    {
      "age": 12,
      "height": 1.73
    }
    
  4. Booleans are recognized case insensitive:

    <root><checked>True</checked><answer>FALSE</answer></root>

    becomes

    {
      "checked": true,
      "answer": false
    }
    
  5. Strings are escaped:

    <root>Quote: &quot; New-line:
    </root>
    

    becomes

    "Quote: \" New-line:\n"
  6. Empty elements will become null:

    <root><nil/><empty></empty></root>

    becomes

    {
      "nil": null,
      "empty": null
    }
    
  7. If all sibling elements have the same name, they become an array

    <root><item>1</item><item>2</item><item>three</item></root>
    

    becomes

    [1, 2, "three"]
    
  8. Mixed mode text-nodes, comments and attributes get absorbed:

    <root version="1.0">testing<!--comment--><element test="true">1</element></root>
    

    becomes

    { "element": true }
    
  9. Namespaces get absorbed, and prefixes will just be part of the property name:

    <root xmlns:ding="http://zanstra.com/ding"><ding:dong>binnen</ding:dong></root>
    

    becomes

    { "ding:dong" : "binnen" }
    
Note: Our algorithms comply with the points 2, 3, 4 and 7. The third and the fourth algorithm comply also with the point 6 (but true instead of null – see the Code considerations). The point 5 is automatically managed by the Javascript method JSON.stringify. Regarding the point 9, we choosed to ignore all nodes which have a prefix; you can include them removing the string && !oNode.prefix from our algorithms (see the Code considerations).

Translation JS extra

All the same as the JSON translation, but with these extra's:

  1. Property names are only escaped when necessary

    <root><while>true</while><wend>false</wend><only-if/></root>
    

    becomes

    {
      "while": true,
      wend: false,
      "only-if": null
    }
    
  2. Within a string, closing elements "</" are escaped as "<\/"

    <root><![CDATA[<script>alert("YES");</script>]]></root>

    becomes

    { script: "<script>alert(\"YES\")<\/script>" }
    
  3. Dates are created as new Date() objects

    <root>2006-12-25</root>

    becomes

    new Date(2006, 12 - 1, 25)
    
  4. Attributes and comments are shown as comments (for testing-purposes):

    <!--testing--><root><test version="1.0">123</test></root>
    

    becomes

    /* testing */ { test /* @version = "1.0" */ : 123}
    
  5. A bit of indentation is done, to keep things ledgible

Note: Our algorithms comply with the point 3 (but without month decrease). The points 1 and 2 are automatically managed by the Javascript method JSON.stringify.

In summary

Let's take the third algorithm as the most representative JXON parsing algorithm. A single structured XML Element might have eight different configurations:

  1. an empty element,
  2. an element with pure text content,
  3. an empty element with attributes,
  4. an element with text content and attributes,
  5. an element containing elements with different names,
  6. an element containing elements with identical names,
  7. an element containing elements and contiguous text,
  8. an element containing elements and non contiguous text.

The following table shows the corresponding conversion patterns between XML and JSON according to the third algorithm.

Case XML JSON Javascript access
1 <animal/> "animal": true myObject.animal
2 <animal>text</animal> "animal": "text" myObject.animal
3 <animal name="value" /> "animal": {"@name": "value"} myObject.animal["@name"]
4 <animal name="value">text</animal> "animal": { "@name": "value", "keyValue": "text" } myObject.animal["@name"], myObject.animal.keyValue
5 <animal> <dog>Charlie</dog> <cat>Deka</cat> </animal> "animal": { "dog": "Charlie", "cat": "Deka" } myObject.animal.dog, myObject.animal.cat
6 <animal> <dog>Charlie</dog> <dog>Mad Max</dog> </animal> "animal": { "dog": ["Charlie", "Mad Max"] } myObject.animal.dog[0], myObject.animal.dog[1]
7 <animal> in my house <dog>Charlie</dog> </animal> "animal": { "keyValue": "in my house", "dog": "Charlie" } myObject.animal.keyValue, myObject.animal.dog
8 <animal> in my ho <dog>Charlie</dog> use </animal> "animal": { "keyValue": "in my house", "dog": "Charlie" } myObject.animal.keyValue, myObject.animal.dog

Code considerations

In these examples we chose to use a property named keyValue for the text content. The lack of standars for XML to JSON conversion leads developers to choose several property names for the text content of XML Element nodes which contain also other child nodes. Sometimes it is used a property called $. Other times it is used a property called #text (a name like this wouldn't be a good choice, since the text content of a node can be parsed into a non-string value from our algorithms during the conversion). In the algorithms proposed here you can easily change this name, depending on your needs.

The choice of using a true value instead of a null value to represent empty nodes is due to the fact that when in an XML document there is an empty node the reason is often to express a Boolean content, as in this case:

<car>
  <type>Ferrari</type>
  <bought />
</car>

If the value were null it would be more cumbersome to launch a code like this:

if (myObject.car.bought) {
  // do something
}
Note: According to our third algorithm and our fourth algorithm, just Text nodes or CDATASection nodes which contain nothing but white spaces (precisely: /^\s+$/) are parsed as null.

The fourth algorithm represents a special case of conversion. As you can see, the generated JavaScript Object tree is not stringifyable. It is very practical for internal JavaScript access, but don't use it if you want to transfer the tree via JSON string (as for Worker messages, for example).

We choosed to ignore nodes which have a prefix (for example: <ding:dong>binnen</ding:dong>), due to their special case. You can include them removing the string && !oNode.prefix from our algorithms (the whole tag will become the property name: { "ding:dong": "binnen" }).

An important consideration is that, using the third or the fourth algorithm, an XML Document can be used to create any type of Javascript object. For example, If you want to create an object like the following:

{
  "bool": true,
  "array": ["Cinema", "Hot dogs", false],
  "object": {
    "nickname": "Jack",
    "registration_date": new Date(1995, 11, 25),
    "privileged_user": true
  },
  "num": 99,
  "text": "Hello World!"
}

you must just create an XML document with the following structure:

<bool>true</bool>
<array>Cinema</array>
<array>Hot dogs</array>
<array>false</array>
<object>
  <nickname>Jack</nickname>
  <registration_date>Dec 25, 1995</registration_date>
  <privileged_user />
</object>
<num>99</num>
<text>Hello World!</text>

This example also shows how the ideal JXON document is an XML document designed specifically to be converted in JSON format, though our algorithms work fine with any kind of XML document.

Appendix: a complete, bidirectional, JXON library

Now we can create a more complete, bidirectional, JXON library based on all our algorithms. Its usage is modelled on the JSON native object.

const JXON = new (function () {
  const
    sValueProp = "keyValue", sAttributesProp = "keyAttributes", sAttrPref = "@", /* you can customize these values */
    aCache = [], rIsNull = /^\s*$/, rIsBool = /^(?:true|false)$/i;

  function parseText (sValue) {
    if (rIsNull.test(sValue)) { return null; }
    if (rIsBool.test(sValue)) { return sValue.toLowerCase() === "true"; }
    if (isFinite(sValue)) { return parseFloat(sValue); }
    if (isFinite(Date.parse(sValue))) { return new Date(sValue); }
    return sValue;
  }

  function objectify (vValue) {
    return vValue === null ? {} : (vValue instanceof Object ? vValue : new vValue.constructor(vValue));
  }

  function createObjTree (oParentNode, nVerb, bFreeze, bNesteAttr) {
    const
      nLevelStart = aCache.length, bChildren = oParentNode.hasChildNodes(),
      bAttributes = oParentNode.hasAttributes(), bHighVerb = Boolean(nVerb & 2);

    var
      sProp, vContent, nLength = 0, sCollectedTxt = "",
      vResult = bHighVerb ? {} : /* put here the default value for empty nodes: */ true;

    if (bChildren) {
      for (var oNode, nChildId = 0; nChildId < oParentNode.childNodes.length; nChildId++) {
        oNode = oParentNode.childNodes.item(nChildId);
        if (oNode.nodeType === 4) { sCollectedTxt += oNode.nodeValue; } /* nodeType is "CDATASection" (4) */
        else if (oNode.nodeType === 3) { sCollectedTxt += oNode.nodeValue.trim(); } /* nodeType is "Text" (3) */
        else if (oNode.nodeType === 1 && !oNode.prefix) { aCache.push(oNode); } /* nodeType is "Element" (1) */
      }
    }

    const nLevelEnd = aCache.length, vBuiltVal = parseText(sCollectedTxt);

    if (!bHighVerb && (bChildren || bAttributes)) { vResult = nVerb === 0 ? objectify(vBuiltVal) : {}; }

    for (var nElId = nLevelStart; nElId < nLevelEnd; nElId++) {
      sProp = aCache[nElId].nodeName.toLowerCase();
      vContent = createObjTree(aCache[nElId], nVerb, bFreeze, bNesteAttr);
      if (vResult.hasOwnProperty(sProp)) {
        if (vResult[sProp].constructor !== Array) { vResult[sProp] = [vResult[sProp]]; }
        vResult[sProp].push(vContent);
      } else {
        vResult[sProp] = vContent;
        nLength++;
      }
    }

    if (bAttributes) {
      const
        nAttrLen = oParentNode.attributes.length,
        sAPrefix = bNesteAttr ? "" : sAttrPref, oAttrParent = bNesteAttr ? {} : vResult;

      for (var oAttrib, nAttrib = 0; nAttrib < nAttrLen; nLength++, nAttrib++) {
        oAttrib = oParentNode.attributes.item(nAttrib);
        oAttrParent[sAPrefix + oAttrib.nodeName.toLowerCase()] = parseText(oAttrib.nodeValue.trim());
      }

      if (bNesteAttr) {
        if (bFreeze) { Object.freeze(oAttrParent); }
        vResult[sAttributesProp] = oAttrParent;
        nLength -= nAttrLen - 1;
      }
    }

    if (nVerb === 3 || (nVerb === 2 || nVerb === 1 && nLength > 0) && sCollectedTxt) {
      vResult[sValueProp] = vBuiltVal;
    } else if (!bHighVerb && nLength === 0 && sCollectedTxt) {
      vResult = vBuiltVal;
    }

    if (bFreeze && (bHighVerb || nLength > 0)) { Object.freeze(vResult); }

    aCache.length = nLevelStart;

    return vResult;
  }

  function loadObjTree (oXMLDoc, oParentEl, oParentObj) {
    var vValue, oChild;

    if (oParentObj instanceof String || oParentObj instanceof Number || oParentObj instanceof Boolean) {
      oParentEl.appendChild(oXMLDoc.createTextNode(oParentObj.toString())); /* verbosity level is 0 */
    } else if (oParentObj.constructor === Date) {
      oParentEl.appendChild(oXMLDoc.createTextNode(oParentObj.toGMTString()));    
    }

    for (var sName in oParentObj) {
      if (isFinite(sName)) { continue; } /* verbosity level is 0 */
      vValue = oParentObj[sName];
      if (sName === sValueProp) {
        if (vValue !== null && vValue !== true) { oParentEl.appendChild(oXMLDoc.createTextNode(vValue.constructor === Date ? vValue.toGMTString() : String(vValue))); }
      } else if (sName === sAttributesProp) { /* verbosity level is 3 */
        for (var sAttrib in vValue) { oParentEl.setAttribute(sAttrib, vValue[sAttrib]); }
      } else if (sName.charAt(0) === sAttrPref) {
        oParentEl.setAttribute(sName.slice(1), vValue);
      } else if (vValue.constructor === Array) {
        for (var nItem = 0; nItem < vValue.length; nItem++) {
          oChild = oXMLDoc.createElement(sName);
          loadObjTree(oXMLDoc, oChild, vValue[nItem]);
          oParentEl.appendChild(oChild);
        }
      } else {
        oChild = oXMLDoc.createElement(sName);
        if (vValue instanceof Object) {
          loadObjTree(oXMLDoc, oChild, vValue);
        } else if (vValue !== null && vValue !== true) {
          oChild.appendChild(oXMLDoc.createTextNode(vValue.toString()));
        }
        oParentEl.appendChild(oChild);
        }
    }
  }

  this.build = function (oXMLParent, nVerbosity /* optional */, bFreeze /* optional */, bNesteAttributes /* optional */) {
    const _nVerb = arguments.length > 1 && typeof nVerbosity === "number" ? nVerbosity & 3 : /* put here the default verbosity level: */ 1;
    return createObjTree(oXMLParent, _nVerb, bFreeze || false, arguments.length > 3 ? bNesteAttributes : _nVerb === 3);    
  };

  this.unbuild = function (oJSONData) {    
    const oNewDoc = document.implementation.createDocument("", "", null);
    loadObjTree(oNewDoc, oNewDoc, oJSONData);
    return oNewDoc;
  };
})();


var myObject = JXON.build(doc);
// we got our javascript object! try: alert(JSON.stringify(myObject));

var newDoc = JXON.unbuild(myObject);
// we got our Document instance! try: alert((new XMLSerializer()).serializeToString(newDoc));

Usage

Syntax

JXON.build(document[, verbosity[, freeze[, nesteAttributes]]])

Description

Returns a JavaScript Object based on the given XML Document.

Parameters

document
The XML document to be converted into JSON format.
verbosity
The verbosity level of conversion (optional), from 0 to 3. It is almost equivalent to our algorithms from #4 to #1 (default value is 1, which is equivalent to the algorithm #3).
freeze
A boolean (optional) expressing whether the created object must be freezed or not (default value is false).
nesteAttributes
A boolean (optional) expressing whether the the attributes must be nested into a child-object named keyAttributes or not (default value is false for verbosity levels from 0 to 2; true for verbosity level 3).

Syntax

JXON.unbuild(JSONData)

Description

Returns an XML Document based on the given JavaScript Object.

Parameters

JSONData
The JavaScript Object from which you want to create your XML Document.

About this library

The JXON.build() method summarizes all our four ways of conversion. The result is therefore the same of our four algorithms, depending on the level of verbosity utilised. The only difference is that the optional properties and methods of the first algorithm (verbosity level: 3) are not included.

The JXON.unbuild() method utilises our reverse algorithm.

Therefore, all code considerations remain the same.

Resources

See also

Revision Source

<p><strong>JXON</strong> (lossless <strong>J</strong>avascript <strong>X</strong>ML <strong>O</strong>bject <strong>N</strong>otation) is a generic name by which is defined the representation of Javascript Objects using <a class="internal" href="/en/XML" title="en/XML">XML</a>. There are not real standards for this conversion, but <a class="internal" href="#The_Parker_Convention" title="The Parker Convention">some conventions begin to appear on the web</a>. There are some cases in which the whole content of an XML document must be readed from the JavaScript interpreter (like for web-apps languages or settings XML documents, for example). In these cases JXON could represent the most practical way.</p>
<div class="note"><strong>Note:</strong> If you are interested to address only some parts of an XML document, use <a class="internal" href="/en/XPath" title="en/XPath">XPath</a> instead of converting the whole document into JSON!</div>
<p>In this article we will see how to convert a parsed XML <a class="internal" href="/en/DOM/document" title="en/DOM/document"><code>document</code></a> (i.e. an instance of <a class="external" href="http://www.w3.org/TR/DOM-Level-2-Core/core.html#i-Document"><code>Document</code></a>) to a JavaScript Object tree (i.e. a tree of nested instances of <a class="internal" href="/en/JavaScript/Reference/Global_Objects/Object" title="en/JavaScript/Reference/Global_Objects/Object"><code>Object</code></a>) and viceversa with some different algorithms.</p>
<p>If you want <strong>a complete bidirectional JXON library</strong> (modelled on the <a class="internal" href="/en/JavaScript/Reference/Global_Objects/JSON" title="en/JavaScript/Reference/Global_Objects/JSON"><code>JSON</code></a> global object), skip to the <a class="internal" href="#JXON_object" title="A complete JXON library">dedicated paragraph</a>.</p>
<h2>Conversion snippets</h2>
<p>Now imagine to have this sample XML document:</p>
<h5 id="XML_Example">example.xml</h5>
<pre class="brush: xml">&lt;?xml version="1.0"?&gt;
&lt;!DOCTYPE catalog SYSTEM "catalog.dtd"&gt;
&lt;catalog&gt;
  &lt;product description="Cardigan Sweater"&gt;
    &lt;catalog_item gender="Men's"&gt;
      &lt;item_number&gt;QWZ5671&lt;/item_number&gt;
      &lt;price&gt;39.95&lt;/price&gt;
      &lt;size description="Medium"&gt;
        &lt;color_swatch image="red_cardigan.jpg"&gt;Red&lt;/color_swatch&gt;
        &lt;color_swatch image="burgundy_cardigan.jpg"&gt;Burgundy&lt;/color_swatch&gt;
      &lt;/size&gt;
      &lt;size description="Large"&gt;
        &lt;color_swatch image="red_cardigan.jpg"&gt;Red&lt;/color_swatch&gt;
        &lt;color_swatch image="burgundy_cardigan.jpg"&gt;Burgundy&lt;/color_swatch&gt;
      &lt;/size&gt;
    &lt;/catalog_item&gt;
    &lt;catalog_item gender="Women's"&gt;
      &lt;item_number&gt;RRX9856&lt;/item_number&gt;
      &lt;discount_until&gt;Dec 25, 1995&lt;/discount_until&gt;
      &lt;price&gt;42.50&lt;/price&gt;
      &lt;size description="Medium"&gt;
        &lt;color_swatch image="black_cardigan.jpg"&gt;Black&lt;/color_swatch&gt;
      &lt;/size&gt;
    &lt;/catalog_item&gt;
  &lt;/product&gt;
  &lt;script type="text/javascript"&gt;&lt;![CDATA[function matchwo(a,b) {
    if (a &lt; b &amp;&amp; a &lt; 0) { return 1; }
    else { return 0; }
}]]&gt;&lt;/script&gt;
&lt;/catalog&gt;
</pre>
<p>First, create a DOM tree like the previous example as described in the <a class="internal" href="/en/How_to_create_a_DOM_tree" title="en/How_to_create_a_DOM_tree">How to Create a DOM tree</a> article. If you have already have a DOM tree from using <a class="internal" href="/en/XMLHttpRequest" title="en/XMLHttpRequest">XMLHttpRequest</a>, skip to the next paragraph.</p>
<p>The algorithms proposed here (see: <a class="internal" href="#JXON_algorithm_1" title="Go to JXON algorithm #1">#1</a>, <a class="internal" href="#JXON_algorithm_2" title="Go to JXON algorithm #2">#2</a>, <a class="internal" href="#JXON_algorithm_3" title="Go to JXON algorithm #3">#3</a>, <a class="internal" href="#JXON_algorithm_4" title="Go to JXON algorithm #4">#4</a>) will consider only the following types of nodes and their attributes:</p>
<ol> <li><code>Document</code> (only as function argument),</li> <li><code>DocumentFragment</code> (only as function argument),</li> <li><code>Element</code>,</li> <li><code>Text</code> (never as function argument),</li> <li><code>CDATASection</code> (never as function argument).</li>
</ol>
<p>It is a good and <em>standardized</em> compromise for a Javascript usage, since all of the information of an XML Document is contained in this types of nodes. All other informations (like processing instructions, schemas, comments, etc.) will be lost (but due to the nature of the information which is lost, this type of algorithms is considered however <strong>lossless</strong>, since what is lost is <em>meta-information</em> and not <em>information</em>).</p>
<p>In order to avoid conflicts, the representation of nodes and attributes names is <em>case insensitive</em> (always rendered in <em>lower case</em>), so object's local properties names setted via JavaScript must always have some kind of capitalization (initial, internal, etc.), as you can see below. Following algorithms are sketchily based on the <a class="internal" href="#The_Parker_Convention" title="The Parker Convention">Parker convention, version 0.4</a> (which prescribes the transformation of <a class="internal" href="/en/Core_JavaScript_1.5_Guide/Working_with_Objects#Objects_and_properties" title="en/Core_JavaScript_1.5_Guide/Working_with_Objects#Objects_and_properties">tags names</a> into <a class="internal" href="/en/DOM/Node.nodeName" title="en/DOM/Node.nodeName">object properties names</a> and the recognition of the <a class="internal" href="/en/JavaScript/Reference/Operators/typeof" title="en/JavaScript/Reference/Operators/typeof"><code>typeof</code></a> of each <code>Node</code>'s <a class="internal" href="/en/DOM/Node.nodeValue" title="en/DOM/Node.nodeValue"><code>nodeValue</code></a> property), but <a class="internal" href="#JXON_Considerations" title="Code considerations">with some differences</a>. Moreover, <strong>all algorithms are equally lossless for the contemplated nodes</strong>.</p>
<p>Now let's serialize <code>doc</code> — the DOM tree — to a Javascript Object Tree (you can read more about <a class="internal" href="/en/JavaScript/Guide/Working_with_Objects" title="Working with Objects">working with Objects</a> and <a class="internal" href="/en/JavaScript/Introduction_to_Object-Oriented_JavaScript" title="Introduction to Object-Oriented JavaScript – MDC">how Javascript is Object-Oriented</a>). We can use several algorithms to convert its content to a Javascript Object Tree.</p>
<h3 id="JXON_algorithm_1">Algorithm #1: a verbose way</h3>
<p>This simple recursive constructor will convert an XML DOM tree to a JavaScript Object tree. The text content of each element is stored into the <code>keyValue</code> property, while <code>nodeAttributes</code>, if exist, are listed under the child object <code>keyAttributes</code>. The constructor's argument can be the entire XML <code>Document</code>, a <code>DocumentFragment</code> or simply an <code>Element</code> node of it.</p>
<pre class="brush: js">function parseText (sValue) {
  if (/^\s*$/.test(sValue)) { return null; }
  if (/^(?:true|false)$/i.test(sValue)) { return sValue.toLowerCase() === "true"; }
  if (isFinite(sValue)) { return parseFloat(sValue); }
  if (isFinite(Date.parse(sValue))) { return new Date(sValue); }
  return sValue;
}

function JXONData (oXMLParent) {
  var nAttrLen = 0, nLength = 0, sCollectedTxt = "";
  if (oXMLParent.hasChildNodes()) {
    for (var oNode, sProp, vContent, nItem = 0; nItem &lt; oXMLParent.childNodes.length; nItem++) {
      oNode = oXMLParent.childNodes.item(nItem);
      if ((oNode.nodeType - 1 | 1) === 3) { sCollectedTxt += oNode.nodeType === 3 ? oNode.nodeValue.trim() : oNode.nodeValue; } // nodeType is "Text" (3) or "CDATASection" (4)
      else if (oNode.nodeType === 1 &amp;&amp; !oNode.prefix) { // nodeType is "Element" (1)
        sProp = oNode.nodeName.toLowerCase();
        vContent = new JXONData(oNode);
        if (this.hasOwnProperty(sProp)) {
          if (this[sProp].constructor !== Array) { this[sProp] = [this[sProp]]; }
          this[sProp].push(vContent);
        } else { this[sProp] = vContent; nLength++; }
      }
    }
    this.keyValue = parseText(sCollectedTxt);
  } else { this.keyValue = null; }
  if (oXMLParent.hasAttributes()) {
    var oAttrib;
    this.keyAttributes = {};
    for (nAttrLen; nAttrLen &lt; oXMLParent.attributes.length; nAttrLen++) {
      oAttrib = oXMLParent.attributes.item(nAttrLen);
      this.keyAttributes[oAttrib.nodeName.toLowerCase()] = parseText(oAttrib.nodeValue.trim());
    }
  }
  // optional properties and methods; you could safely adjoust/remove them...
  this.keyLength = nLength;
  this.attributesLength = nAttrLen;
  // this.DOMNode = oXMLParent;
  this.valueOf = function () { return this.keyValue; };
  this.toString = function () { return String(this.keyValue); };
  this.getItem = function (nChildId) {
    if (nLength === 0) { return null; }
    var nCount = 0;
    for (var sKey in this) { if (nCount === nChildId) { return this[sKey]; } nCount++; }
    return null;
  };
  this.getAttribute = function (nAttrId) {
    if (nAttrLen === 0 || nAttrId + 1 &gt; nAttrLen) { return null; }
    var nAttr = 0;
    for (var sAttrName in this.keyAttributes) { if (nAttr === nAttrId) { return this.keyAttributes[sAttrName]; } nAttr++; }
    return null;
  };
  this.hasChildren = function () { return this.keyLength &gt; 0; };

  /* Object.freeze(this); */
}

var myObject = new JXONData(doc);
// we got our javascript object! try: alert(JSON.stringify(myObject));
</pre>
<div class="note"><strong>Note:</strong> If you want to freeze the whole object tree (because of the "static" nature of a XML document), uncomment the string: <code>/* Object.freeze(this); */</code>. The <code><a class="internal" href="/en/JavaScript/Reference/Global_Objects/Object/freeze" title="en/JavaScript/Reference/Global_Objects/Object/freeze">Object.freeze</a></code> method prevents new properties from being added to it, prevents existing properties from being removed and prevents existing properties, or their enumerability, configurability, or writability, from being changed. In essence the object tree is made effectively immutable.</div>
<p>With this algorithm <a class="internal" href="#XML_Example" title="Go to the sample XML document">our example</a> will become:</p>
<pre class="brush: js">{
  "catalog": {
    "product": {
      "catalog_item": [{
        "item_number": {
          "keyValue": "QWZ5671",
          "keyLength": 0,
          "attributesLength": 0
        },
        "price": {
          "keyValue": 39.95,
          "keyLength": 0,
          "attributesLength": 0
        },
        "size": [{
          "color_swatch": [{
            "keyValue": "Red",
            "keyAttributes": {
              "image": "red_cardigan.jpg"
            },
            "keyLength": 0,
            "attributesLength": 1
          }, {
            "keyValue": "Burgundy",
            "keyAttributes": {
              "image": "burgundy_cardigan.jpg"
            },
            "keyLength": 0,
            "attributesLength": 1
          }],
          "keyValue": null,
          "keyAttributes": {
            "description": "Medium"
          },
          "keyLength": 1,
          "attributesLength": 1
        }, {
          "color_swatch": [{
            "keyValue": "Red",
            "keyAttributes": {
              "image": "red_cardigan.jpg"
            },
            "keyLength": 0,
            "attributesLength": 1
          }, {
            "keyValue": "Burgundy",
            "keyAttributes": {
              "image": "burgundy_cardigan.jpg"
            },
            "keyLength": 0,
            "attributesLength": 1
          }],
          "keyValue": null,
          "keyAttributes": {
            "description": "Large"
          },
          "keyLength": 1,
          "attributesLength": 1
        }],
        "keyValue": null,
        "keyAttributes": {
          "gender": "Men's"
        },
        "keyLength": 3,
        "attributesLength": 1
      }, {
        "item_number": {
          "keyValue": "RRX9856",
          "keyLength": 0,
          "attributesLength": 0
        },
        "discount_until": {
          "keyValue": new Date(1995, 11, 25),
          "keyLength": 0,
          "attributesLength": 0
        },
        "price": {
          "keyValue": 42.5,
          "keyLength": 0,
          "attributesLength": 0
        },
        "size": {
          "color_swatch": {
            "keyValue": "Black",
            "keyAttributes": {
              "image": "black_cardigan.jpg"
            },
            "keyLength": 0,
            "attributesLength": 1
          },
          "keyValue": null,
          "keyAttributes": {
            "description": "Medium"
          },
          "keyLength": 1,
          "attributesLength": 1
        },
        "keyValue": null,
        "keyAttributes": {
          "gender": "Women's"
        },
        "keyLength": 4,
        "attributesLength": 1
      }],
      "keyValue": null,
      "keyAttributes": {
        "description": "Cardigan Sweater"
      },
      "keyLength": 1,
      "attributesLength": 1
    },
    "script": {
      "keyValue": "function matchwo(a,b) {\n  if (a &lt; b &amp;&amp; a &lt; 0) { return 1; }\n  else { return 0; }\n}",
      "keyAttributes": {
        "type": "text/javascript"
      },
      "keyLength": 0,
      "attributesLength": 1
    },
    "keyValue": null,
    "keyLength": 2,
    "attributesLength": 0
  },
  "keyValue": null,
  "keyLength": 1,
  "attributesLength": 0
}
</pre>
<p>It is a recommanded way if you don't know the structure of the XML document.</p>
<h3 id="JXON_algorithm_2">Algorithm #2: a less verbose way</h3>
<p>Here is another, simpler, conversion method, where <code>nodeAttributes</code> are listed under the same object of children nodes, but have the “@” prefix. As above, the text content is stored into the <code>keyValue</code> property. The constructor's argument can be the entire XML <code>Document</code>, a <code>DocumentFragment</code> or simply an <code>Element</code> node of it.</p>
<pre class="brush: js">function parseText (sValue) {
  if (/^\s*$/.test(sValue)) { return null; }
  if (/^(?:true|false)$/i.test(sValue)) { return sValue.toLowerCase() === "true"; }
  if (isFinite(sValue)) { return parseFloat(sValue); }
  if (isFinite(Date.parse(sValue))) { return new Date(sValue); }
  return sValue;
}

function JXONData (oXMLParent) {
  if (oXMLParent.hasChildNodes()) {
    var sCollectedTxt = "";
    for (var oNode, sProp, vContent, nItem = 0; nItem &lt; oXMLParent.childNodes.length; nItem++) {
      oNode = oXMLParent.childNodes.item(nItem);
      if ((oNode.nodeType - 1 | 1) === 3) { sCollectedTxt += oNode.nodeType === 3 ? oNode.nodeValue.trim() : oNode.nodeValue; }
      else if (oNode.nodeType === 1 &amp;&amp; !oNode.prefix) {
        sProp = oNode.nodeName.toLowerCase();
        vContent = new JXONData(oNode);
        if (this.hasOwnProperty(sProp)) {
          if (this[sProp].constructor !== Array) { this[sProp] = [this[sProp]]; }
          this[sProp].push(vContent);
        } else { this[sProp] = vContent; }
      }
    }
    if (sCollectedTxt) { this.keyValue = parseText(sCollectedTxt); }
  }
  if (oXMLParent.hasAttributes()) {
    var oAttrib;
    for (var nAttrib = 0; nAttrib &lt; oXMLParent.attributes.length; nAttrib++) {
      oAttrib = oXMLParent.attributes.item(nAttrib);
      this["@" + oAttrib.nodeName.toLowerCase()] = parseText(oAttrib.nodeValue.trim());
    }
  }
  /* Object.freeze(this); */
}

var myObject = new JXONData(doc);
// we got our javascript object! try: alert(JSON.stringify(myObject));
</pre>
<div class="note"><strong>Note:</strong> If you want to freeze the whole object tree (because of the "static" nature of a XML document), uncomment the string: <code>/* Object.freeze(this); */</code>. The <code><a class="internal" href="/en/JavaScript/Reference/Global_Objects/Object/freeze" title="en/JavaScript/Reference/Global_Objects/Object/freeze">Object.freeze</a></code> method prevents new properties from being added to it, prevents existing properties from being removed and prevents existing properties, or their enumerability, configurability, or writability, from being changed. In essence the object tree is made effectively immutable.</div>
<p>With this algorithm <a class="internal" href="#XML_Example" title="Go to the sample XML document">our example</a> will become:</p>
<pre class="brush: js">{
  "catalog": {
    "product": {
      "catalog_item": [{
        "item_number": {
          "keyValue": "QWZ5671"
        },
        "price": {
          "keyValue": 39.95
        },
        "size": [{
          "color_swatch": [{
            "keyValue": "Red",
            "@image": "red_cardigan.jpg"
          }, {
            "keyValue": "Burgundy",
            "@image": "burgundy_cardigan.jpg"
          }],
          "@description": "Medium"
        }, {
          "color_swatch": [{
            "keyValue": "Red",
            "@image": "red_cardigan.jpg"
          }, {
            "keyValue": "Burgundy",
            "@image": "burgundy_cardigan.jpg"
          }],
          "@description": "Large"
        }],
        "@gender": "Men's"
      }, {
        "item_number": {
          "keyValue": "RRX9856"
        },
        "discount_until": {
          "keyValue": new Date(1995, 11, 25)
        },
        "price": {
          "keyValue": 42.5
        },
        "size": {
          "color_swatch": {
            "keyValue": "Black",
            "@image": "black_cardigan.jpg"
          },
          "@description": "Medium"
        },
        "@gender": "Women's"
      }],
      "@description": "Cardigan Sweater"
    },
    "script": {
      "keyValue": "function matchwo(a,b) {\n  if (a &lt; b &amp;&amp; a &lt; 0) { return 1; }\n  else { return 0; }\n}",
      "@type": "text/javascript"
    }
  }
}
</pre>
<p>It is a possible way if you partially know the structure of the XML document.</p>
<h3 id="JXON_algorithm_3">Algorithm #3: a synthetic way</h3>
<p>Here is another method of conversion. This algorithm is the closest to the <a class="internal" href="#The_Parker_Convention" title="The Parker Convention">Parker convention</a>. It is very similar to the previous one, except that nodes which do not contain other recognizable nodes than <code>Text</code> or <code>CDATASection</code> are not treated as objects, but directly as booleans, strings, numbers or <code>Date</code> objects (see the <a class="internal" href="#The_Parker_Convention" title="The Parker Convention">Parker convention</a>). Empty nodes (i.e. which do not contain other <code>Element</code> nodes, <code>Text</code> nodes or <code>CDATASection</code> nodes) have the default value <code>true</code> (see the <a class="internal" href="#JXON_Considerations" title="Code considerations">Code considerations</a>). Also, this time it is not used a constructor, but a function. The function's argument can be the entire XML <code>Document</code>, a <code>DocumentFragment</code> or simply an <code>Element</code> node of it. <strong>In many cases this one represents the most practical conversion method</strong>.</p>
<pre class="brush: js">function parseText (sValue) {
  if (/^\s*$/.test(sValue)) { return null; }
  if (/^(?:true|false)$/i.test(sValue)) { return sValue.toLowerCase() === "true"; }
  if (isFinite(sValue)) { return parseFloat(sValue); }
  if (isFinite(Date.parse(sValue))) { return new Date(sValue); }
  return sValue;
}

function getJXONData (oXMLParent) {
  var vResult = /* put here the default value for empty nodes! */ true, nLength = 0, sCollectedTxt = "";
  if (oXMLParent.hasAttributes()) {
    vResult = {};
    for (nLength; nLength &lt; oXMLParent.attributes.length; nLength++) {
      oAttrib = oXMLParent.attributes.item(nLength);
      vResult["@" + oAttrib.nodeName.toLowerCase()] = parseText(oAttrib.nodeValue.trim());
    }
  }
  if (oXMLParent.hasChildNodes()) {
    for (var oNode, sProp, vContent, nItem = 0; nItem &lt; oXMLParent.childNodes.length; nItem++) {
      oNode = oXMLParent.childNodes.item(nItem);
      if (oNode.nodeType === 4) { sCollectedTxt += oNode.nodeValue; } /* nodeType is "CDATASection" (4) */
      else if (oNode.nodeType === 3) { sCollectedTxt += oNode.nodeValue.trim(); } /* nodeType is "Text" (3) */
      else if (oNode.nodeType === 1 &amp;&amp; !oNode.prefix) { /* nodeType is "Element" (1) */
        if (nLength === 0) { vResult = {}; }
        sProp = oNode.nodeName.toLowerCase();
        vContent = getJXONData(oNode);
        if (vResult.hasOwnProperty(sProp)) {
          if (vResult[sProp].constructor !== Array) { vResult[sProp] = [vResult[sProp]]; }
          vResult[sProp].push(vContent);
        } else { vResult[sProp] = vContent; nLength++; }
      }
    }
  }
  if (sCollectedTxt) { nLength &gt; 0 ? vResult.keyValue = parseText(sCollectedTxt) : vResult = parseText(sCollectedTxt); }
  /* if (nLength &gt; 0) { Object.freeze(vResult); } */
  return vResult;
}

var myObject = getJXONData(doc);
// we got our javascript object! try: alert(JSON.stringify(myObject));
</pre>
<div class="note"><strong>Note:</strong> If you want to freeze the whole object tree (because of the "static" nature of a XML document), uncomment the string: <code>/* if (nLength &gt; 0) { Object.freeze(vResult); } */</code>. The <code><a class="internal" href="/en/JavaScript/Reference/Global_Objects/Object/freeze" title="en/JavaScript/Reference/Global_Objects/Object/freeze">Object.freeze</a></code> method prevents new properties from being added to it, prevents existing properties from being removed and prevents existing properties, or their enumerability, configurability, or writability, from being changed. In essence the object tree is made effectively immutable.</div>
<p>With this algorithm <a class="internal" href="#XML_Example" title="Go to the sample XML document">our example</a> will become:</p>
<pre class="brush: js">{
  "catalog": {
    "product": {
      "@description": "Cardigan Sweater",
      "catalog_item": [{
        "@gender": "Men's",
        "item_number": "QWZ5671",
        "price": 39.95,
        "size": [{
          "@description": "Medium",
          "color_swatch": [{
            "@image": "red_cardigan.jpg",
            "keyValue": "Red"
          }, {
            "@image": "burgundy_cardigan.jpg",
            "keyValue": "Burgundy"
          }]
        }, {
          "@description": "Large",
          "color_swatch": [{
            "@image": "red_cardigan.jpg",
            "keyValue": "Red"
          }, {
            "@image": "burgundy_cardigan.jpg",
            "keyValue": "Burgundy"
          }]
        }]
      }, {
        "@gender": "Women's",
        "item_number": "RRX9856",
        "discount_until": new Date(1995, 11, 25),
        "price": 42.5,
        "size": {
          "@description": "Medium",
          "color_swatch": {
            "@image": "black_cardigan.jpg",
            "keyValue": "Black"
          }
        }
      }]
    },
    "script": {
      "@type": "text/javascript",
      "keyValue": "function matchwo(a,b) {\n  if (a &lt; b &amp;&amp; a &lt; 0) { return 1; }\n  else { return 0; }\n}"
    }
  }
}
</pre>
<p>It is a recommanded way if you know the structure of the XML document.</p>
<h3 id="JXON_algorithm_4">Algorithm #4: a very minimalist way</h3>
<p>The following is another possible way of conversion. It is very close to the <a class="internal" href="#The_Parker_Convention" title="The Parker Convention">Parker convention</a>, too. With this algorithm all <code>Element</code> nodes which contain other child <code>Element</code> nodes and <code>Text</code> or <code>CDATASection</code> nodes in the same level are treated as instances of <code>Boolean</code>, <code>Number</code>, <code>String</code>, or <code>Date</code> Constructors. So any child <code>Element</code> node, if exists, will be nested in these types of objects.</p>
<p>For example:</p>
<pre class="brush: xml">&lt;employee type="usher"&gt;John Smith&lt;/employee&gt;
&lt;manager&gt;Lisa Carlucci&lt;/manager&gt;
</pre>
<p>will become</p>
<pre class="brush: js">var myObject = {
  "employee": new String("John Smith"),
  "manager": "Lisa Carlucci"
};

myObject.employee["@type"] = "usher";

// test

alert(myObject.manager); // "Lisa Carlucci"
alert(myObject.employee["@type"]); // "usher"
alert(myObject.employee); // "John Smith"
</pre>
<div class="note"><strong>Note:</strong> This algorithm represents <em>a special case of conversion</em>. <strong>The generated JavaScript Object tree is not <a class="internal" href="/en/JavaScript/Reference/Global_Objects/JSON/stringify" title="en/JavaScript/Reference/Global_Objects/JSON/stringify">stringifyable</a></strong> (see the <a class="internal" href="#JXON_Considerations" title="Code considerations">Code considerations</a>). It is very practical for internal JavaScript access, but don't use it if you want to transfer the tree via JSON string!</div>
<p>As for the third algorithm, nodes which do not contain other recognizable nodes than <code>Text</code> or <code>CDATASection</code> are not treated as objects, but directly as booleans, strings, numbers (primitive values) or <code>Date</code> objects; and empty nodes (i.e. which do not contain other <code>Element</code> nodes, <code>Text</code> nodes or <code>CDATASection</code> nodes) have the default value <code>true</code>. As for the third algorithm it is not used a constructor, but a function. The function's argument can be the entire XML <code>Document</code>, a <code>DocumentFragment</code> or simply an <code>Element</code> node of it.</p>
<pre class="brush: js">function parseText (sValue) {
  if (/^\s*$/.test(sValue)) { return null; }
  if (/^(?:true|false)$/i.test(sValue)) { return sValue.toLowerCase() === "true"; }
  if (isFinite(sValue)) { return parseFloat(sValue); }
  if (isFinite(Date.parse(sValue))) { return new Date(sValue); }
  return sValue;
}

function objectify (vValue) {
  if (vValue === null) {
    return new (function() {
      this.toString = function() { return "null"; }
      this.valueOf = function() { return null; }
    })();
  }
  return vValue instanceof Object ? vValue : new vValue.constructor(vValue);
}

var aTmpEls = []; // loaded element nodes cache

function getJXONData (oXMLParent) {
  var  sProp, vContent, vResult, nLength = 0, nLevelStart = aTmpEls.length,
       nChildren = oXMLParent.hasChildNodes() ? oXMLParent.childNodes.length : 0, sCollectedTxt = "";

  for (var oNode, nItem = 0; nItem &lt; nChildren; nItem++) {
    oNode = oXMLParent.childNodes.item(nItem);
    if (oNode.nodeType === 4) { sCollectedTxt += oNode.nodeValue; } /* nodeType is "CDATASection" (4) */
    else if (oNode.nodeType === 3) { sCollectedTxt += oNode.nodeValue.trim(); } /* nodeType is "Text" (3) */
    else if (oNode.nodeType === 1 &amp;&amp; !oNode.prefix) { aTmpEls.push(oNode); } /* nodeType is "Element" (1) */
  }

  var nLevelEnd = aTmpEls.length, vBuiltVal = parseText(sCollectedTxt);

  if (oXMLParent.hasAttributes()) {
    vResult = objectify(vBuiltVal);
    for (nLength; nLength &lt; oXMLParent.attributes.length; nLength++) {
      oAttrib = oXMLParent.attributes.item(nLength);
      vResult["@" + oAttrib.nodeName.toLowerCase()] = parseText(oAttrib.nodeValue.trim());
    }
  } else if (nLevelEnd &gt; nLevelStart) { vResult = objectify(vBuiltVal); }

  for (var nElId = nLevelStart; nElId &lt; nLevelEnd; nElId++) {
    sProp = aTmpEls[nElId].nodeName.toLowerCase();
    vContent = getJXONData(aTmpEls[nElId]);
    if (vResult.hasOwnProperty(sProp)) {
    if (vResult[sProp].constructor !== Array) { vResult[sProp] = [vResult[sProp]]; }
      vResult[sProp].push(vContent);
    } else { vResult[sProp] = vContent; nLength++; }
  }

  aTmpEls.length = nLevelStart;

  if (nLength === 0) { vResult = sCollectedTxt ? vBuiltVal : /* put here the default value for empty nodes: */ true; }
  /* else { Object.freeze(vResult); } */

  return vResult;
}

var myObject = getJXONData(doc);
alert(myObject.catalog.product.catalog_item[1].size.color_swatch["@image"]); // "black_cardigan.jpg"
alert(myObject.catalog.product.catalog_item[1].size.color_swatch); // "Black" !
</pre>
<div class="note"><strong>Note:</strong> If you want to freeze the whole object tree (because of the "static" nature of a XML document), uncomment the string: <code>/* else { Object.freeze(vResult); } */</code>. The <code><a class="internal" href="/en/JavaScript/Reference/Global_Objects/Object/freeze" title="en/JavaScript/Reference/Global_Objects/Object/freeze">Object.freeze</a></code> method prevents new properties from being added to it, prevents existing properties from being removed and prevents existing properties, or their enumerability, configurability, or writability, from being changed. In essence the object tree is made effectively immutable.</div>
<p>It is a possible way if you know the structure of the XML document.</p>
<h3 id="JXON_reverse_algorithms">Reverse Algorithms</h3>
<p>It is possible to reverse the algorithms proposed here in order to build a new XML document starting from a JavaScript Objects Tree. For simplicity, we will propose here a single example, which in a unique code represents the inversion of all our algorithms.</p>
<pre class="brush: js">function createXML (oJSONData) {
  function loadObjTree (oParentEl, oParentObj) {
    var vValue, oChild;
    if (oParentObj instanceof String || oParentObj instanceof Number || oParentObj instanceof Boolean) {
      oParentEl.appendChild(oNewDoc.createTextNode(oParentObj.toString())); /* verbosity level is 0 */
    } else if (oParentObj.constructor === Date) {
      oParentEl.appendChild(oNewDoc.createTextNode(oParentObj.toGMTString()));    
    }
    for (var sName in oParentObj) {
      if (isFinite(sName)) { continue; } /* verbosity level is 0 */
      vValue = oParentObj[sName];
      if (sName === "keyValue") {
        if (vValue !== null &amp;&amp; vValue !== true) { oParentEl.appendChild(oNewDoc.createTextNode(vValue.constructor === Date ? vValue.toGMTString() : String(vValue))); }
      } else if (sName === "keyAttributes") { /* verbosity level is 3 */
        for (var sAttrib in vValue) { oParentEl.setAttribute(sAttrib, vValue[sAttrib]); }
      } else if (sName.charAt(0) === "@") {
        oParentEl.setAttribute(sName.slice(1), vValue);
      } else if (vValue.constructor === Array) {
        for (var nItem = 0; nItem &lt; vValue.length; nItem++) {
          oChild = oNewDoc.createElement(sName);
          loadObjTree(oChild, vValue[nItem]);
          oParentEl.appendChild(oChild);
        }
      } else {
        oChild = oNewDoc.createElement(sName);
        if (vValue instanceof Object) {
          loadObjTree(oChild, vValue);
        } else if (vValue !== null &amp;&amp; vValue !== true) {
          oChild.appendChild(oNewDoc.createTextNode(vValue.toString()));
        }
        oParentEl.appendChild(oChild);
      }
    }
  }
  const oNewDoc = document.implementation.createDocument("", "", null);
  loadObjTree(oNewDoc, oJSONData);
  return oNewDoc;
}

var newDoc = createXML(myObject);
// we got our Document instance! try: alert((new XMLSerializer()).serializeToString(newDoc));
</pre>
<div class="note"><strong>Note:</strong> With this code the <code>Date</code> instances, if exist, will be converted into Strings through the <code>toGMTString()</code> method. Nothing prohibits the use of any other conversion method. In addition, all properties of the tree with a <code>true</code> value will be converted into empty elements with no text nodes (see the <a class="internal" href="#JXON_Considerations" title="Code considerations">Code considerations</a>).</div>
<p>It is a good solution if you want to automate the creation of an XML document. It is a bad choice, instead, if you want to re-build an XML document previously converted into JSON. Although the conversion is very faithful (except for <code>CDATASection</code> nodes , which will be converted into <code>Text</code> nodes), the process is unnecessarily costly. In fact, if our goal is to edit an XML document, it is strongly recommended to work on it rather than create new ones.</p>
<h2 id="The_Parker_Convention">The Parker Convention</h2>
<p>The functions listed above for the conversion of an XML document to <a class="internal" href="/en/JSON" title="en/JSON">JSON</a> (often called «JXON algorithms») are more or less freely based on the Parker Convention. It is called “Parker Convention” in opposition to “BadgerFish Convention”, after the comic Parker &amp; Badger by Cuadrado. See also: <a class="external" href="http://badgerfish.ning.com/" title="BadgerFish convention">BadgerFish Convention</a>.</p>
<p>The following is a transcription of the Parker Convention paper (version 0.4), from the page “<a class="external" href="http://code.google.com/p/xml2json-xslt/wiki/TransformingRules" title="TransformingRules – xml2json-xslt">TransformingRules</a>” of the <a class="external" href="http://code.google.com/p/xml2json-xslt/" title="xml2json-xslt project">xml2json-xslt project</a> site.</p>
<p>This Convention was written in order to regulate the conversion to <a class="internal" href="/en/JSON" title="en/JSON">JSON</a> from <a class="internal" href="/en/XSLT" title="en/XSLT">XSLT</a>, so parts of it are futile for Javascript.</p>
<h3>Translation JSON</h3>
<ol> <li> <p>The root element will be absorbed, for there is only one:</p> <pre class="brush: xml">&lt;root&gt;test&lt;/root&gt;</pre> <p>becomes</p> <pre class="brush: js">"test"
</pre> </li> <li> <p>Element names become object properties:</p> <pre class="brush: xml">&lt;root&gt;&lt;name&gt;Xml&lt;/name&gt;&lt;encoding&gt;ASCII&lt;/encoding&gt;&lt;/root&gt;</pre> <p>becomes</p> <pre class="brush: js">{
  "name": "Xml",
  "encoding": "ASCII"
}
</pre> </li> <li> <p>Numbers are recognized (integers and decimals):</p> <pre class="brush: xml">&lt;root&gt;&lt;age&gt;12&lt;/age&gt;&lt;height&gt;1.73&lt;/height&gt;&lt;/root&gt;</pre> <p>becomes</p> <pre class="brush: js">{
  "age": 12,
  "height": 1.73
}
</pre> </li> <li> <p>Booleans are recognized case insensitive:</p> <pre class="brush: xml">&lt;root&gt;&lt;checked&gt;True&lt;/checked&gt;&lt;answer&gt;FALSE&lt;/answer&gt;&lt;/root&gt;</pre> <p>becomes</p> <pre class="brush: js">{
  "checked": true,
  "answer": false
}
</pre> </li> <li> <p>Strings are escaped:</p> <pre class="brush: xml">&lt;root&gt;Quote: &amp;quot; New-line:
&lt;/root&gt;
</pre> <p>becomes</p> <pre class="brush: js">"Quote: \" New-line:\n"</pre> </li> <li> <p>Empty elements will become null:</p> <pre class="brush: xml">&lt;root&gt;&lt;nil/&gt;&lt;empty&gt;&lt;/empty&gt;&lt;/root&gt;</pre> <p>becomes</p> <pre class="brush: js">{
  "nil": null,
  "empty": null
}
</pre> </li> <li> <p>If all sibling elements have the same name, they become an array</p> <pre class="brush: xml">&lt;root&gt;&lt;item&gt;1&lt;/item&gt;&lt;item&gt;2&lt;/item&gt;&lt;item&gt;three&lt;/item&gt;&lt;/root&gt;
</pre> <p>becomes</p> <pre class="brush: js">[1, 2, "three"]
</pre> </li> <li> <p>Mixed mode text-nodes, comments and attributes get absorbed:</p> <pre class="brush: xml">&lt;root version="1.0"&gt;testing&lt;!--comment--&gt;&lt;element test="true"&gt;1&lt;/element&gt;&lt;/root&gt;
</pre> <p>becomes</p> <pre class="brush: js">{ "element": true }
</pre> </li> <li> <p>Namespaces get absorbed, and prefixes will just be part of the property name:</p> <pre class="brush: xml">&lt;root xmlns:ding="http://zanstra.com/ding"&gt;&lt;ding:dong&gt;binnen&lt;/ding:dong&gt;&lt;/root&gt;
</pre> <p>becomes</p> <pre class="brush: js">{ "ding:dong" : "binnen" }
</pre> </li>
</ol>
<div class="note"><strong>Note:</strong> Our algorithms comply with the points 2, 3, 4 and 7. The third and the fourth algorithm comply also with the point 6 (but <code>true</code> instead of <code>null</code> – see the <a class="internal" href="#JXON_Considerations" title="Code considerations">Code considerations</a>). The point 5 is automatically managed by the Javascript method <code><a class="internal" href="/en/JavaScript/Reference/Global_Objects/JSON/stringify" title="en/JavaScript/Reference/Global_Objects/JSON/stringify">JSON.stringify</a></code>. Regarding the point 9, we choosed to ignore all nodes which have a prefix; you can include them removing the string <code>&amp;&amp; !oNode.prefix</code> from our algorithms (see the <a class="internal" href="#JXON_Considerations" title="Code considerations">Code considerations</a>).</div>
<h3>Translation JS extra</h3>
<p>All the same as the JSON translation, but with these extra's:</p>
<ol> <li> <p>Property names are only escaped when necessary</p> <pre class="brush: xml">&lt;root&gt;&lt;while&gt;true&lt;/while&gt;&lt;wend&gt;false&lt;/wend&gt;&lt;only-if/&gt;&lt;/root&gt;
</pre> <p>becomes</p> <pre class="brush: js">{
  "while": true,
  wend: false,
  "only-if": null
}
</pre> </li> <li> <p>Within a string, closing elements "&lt;/" are escaped as "&lt;\/"</p> <pre class="brush: xml">&lt;root&gt;&lt;![CDATA[&lt;script&gt;alert("YES");&lt;/script&gt;]]&gt;&lt;/root&gt;</pre> <p>becomes</p> <pre class="brush: js">{ script: "&lt;script&gt;alert(\"YES\")&lt;\/script&gt;" }
</pre> </li> <li> <p>Dates are created as new Date() objects</p> <pre class="brush: xml">&lt;root&gt;2006-12-25&lt;/root&gt;</pre> <p>becomes</p> <pre class="brush: js">new Date(2006, 12 - 1, 25)
</pre> </li> <li> <p>Attributes and comments are shown as comments (for testing-purposes):</p> <pre class="brush: xml">&lt;!--testing--&gt;&lt;root&gt;&lt;test version="1.0"&gt;123&lt;/test&gt;&lt;/root&gt;
</pre> <p>becomes</p> <pre class="brush: js">/* testing */ { test /* @version = "1.0" */ : 123}
</pre> </li> <li> <p>A bit of indentation is done, to keep things ledgible</p> </li>
</ol>
<div class="note"><strong>Note:</strong> Our algorithms comply with the point 3 (but without month decrease). The points 1 and 2 are automatically managed by the Javascript method <code><a class="internal" href="/en/JavaScript/Reference/Global_Objects/JSON/stringify" title="en/JavaScript/Reference/Global_Objects/JSON/stringify">JSON.stringify</a></code>.</div>
<h2>In summary</h2>
<p>Let's take <strong><a class="internal" href="#JXON_algorithm_3" title="Go to JXON algorithm #3">the third algorithm</a> as the most representative JXON parsing algorithm</strong>. A single structured XML <code>Element</code> might have <em>eight different configurations</em>:</p>
<ol> <li>an empty element,</li> <li>an element with pure text content,</li> <li>an empty element with attributes,</li> <li>an element with text content and attributes,</li> <li>an element containing elements with different names,</li> <li>an element containing elements with identical names,</li> <li>an element containing elements and contiguous text,</li> <li>an element containing elements and non contiguous text.</li>
</ol>
<p>The following table shows the corresponding conversion patterns between XML and JSON according to the <a class="internal" href="#JXON_algorithm_3" title="Go to JXON algorithm #3">third algorithm</a>.</p>
<table> <thead> <tr> <th style="background: #faf9e2; color: #5d5636; text-align: center;"><strong>Case</strong></th> <th style="background: #faf9e2; color: #5d5636; text-align: center;"><strong>XML</strong></th> <th style="background: #faf9e2; color: #5d5636; text-align: center;"><strong>JSON</strong></th> <th style="background: #faf9e2; color: #5d5636; text-align: center;"><strong>Javascript access</strong></th> </tr> </thead> <tbody> <tr> <td style="background: #f6f6f6; color: #000000;">1</td> <td style="background: #f6f6f6; color: #000000;"><code>&lt;animal/&gt;</code></td> <td style="background: #f6f6f6; color: #000000;"><code>"animal": true</code></td> <td style="background: #f6f6f6; color: #000000;"><code>myObject.animal</code></td> </tr> <tr> <td style="background: #e7e5dc; color: #silver;">2</td> <td style="background: #e7e5dc; color: #silver;"><code>&lt;animal&gt;text&lt;/animal&gt;</code></td> <td style="background: #e7e5dc; color: #silver;"><code>"animal": "text"</code></td> <td style="background: #e7e5dc; color: #silver;"><code>myObject.animal</code></td> </tr> <tr> <td style="background: #f6f6f6; color: #000000;">3</td> <td style="background: #f6f6f6; color: #000000;"><code>&lt;animal name="value" /&gt;</code></td> <td style="background: #f6f6f6; color: #000000;"><code>"animal": {"@name": "value"}</code></td> <td style="background: #f6f6f6; color: #000000;"><code>myObject.animal["@name"]</code></td> </tr> <tr> <td style="background: #e7e5dc; color: #silver;">4</td> <td style="background: #e7e5dc; color: #silver;"><code>&lt;animal name="value"&gt;text&lt;/animal&gt;</code></td> <td style="background: #e7e5dc; color: #silver;"><code>"animal": { "@name": "value", "keyValue": "text" }</code></td> <td style="background: #e7e5dc; color: #silver;"><code>myObject.animal["@name"]</code>, <code>myObject.animal.keyValue</code></td> </tr> <tr> <td style="background: #f6f6f6; color: #000000;">5</td> <td style="background: #f6f6f6; color: #000000;"><code>&lt;animal&gt; &lt;dog&gt;Charlie&lt;/dog&gt; &lt;cat&gt;Deka&lt;/cat&gt; &lt;/animal&gt;</code></td> <td style="background: #f6f6f6; color: #000000;"><code>"animal": { "dog": "Charlie", "cat": "Deka" }</code></td> <td style="background: #f6f6f6; color: #000000;"><code>myObject.animal.dog</code>, <code>myObject.animal.cat</code></td> </tr> <tr> <td style="background: #e7e5dc; color: #silver;">6</td> <td style="background: #e7e5dc; color: #silver;"><code>&lt;animal&gt; &lt;dog&gt;Charlie&lt;/dog&gt; &lt;dog&gt;Mad Max&lt;/dog&gt; &lt;/animal&gt;</code></td> <td style="background: #e7e5dc; color: #silver;"><code>"animal": { "dog": ["Charlie", "Mad Max"] }</code></td> <td style="background: #e7e5dc; color: #silver;"><code>myObject.animal.dog[0]</code>, <code>myObject.animal.dog[1]</code></td> </tr> <tr> <td style="background: #f6f6f6; color: #000000;">7</td> <td style="background: #f6f6f6; color: #000000;"><code>&lt;animal&gt; in my house &lt;dog&gt;Charlie&lt;/dog&gt; &lt;/animal&gt;</code></td> <td style="background: #f6f6f6; color: #000000;"><code>"animal": { "keyValue": "in my house", "dog": "Charlie" }</code></td> <td style="background: #f6f6f6; color: #000000;"><code>myObject.animal.keyValue</code>, <code>myObject.animal.dog</code></td> </tr> <tr> <td style="background: #e7e5dc; color: #silver;">8</td> <td style="background: #e7e5dc; color: #silver;"><code>&lt;animal&gt; in my ho &lt;dog&gt;Charlie&lt;/dog&gt; use &lt;/animal&gt;</code></td> <td style="background: #e7e5dc; color: #silver;"><code>"animal": { "keyValue": "in my house", "dog": "Charlie" }</code></td> <td style="background: #e7e5dc; color: #silver;"><code>myObject.animal.keyValue</code>, <code>myObject.animal.dog</code></td> </tr> </tbody>
</table>
<h2 id="JXON_Considerations">Code considerations</h2>
<p>In these examples we chose to use a property named <code>keyValue</code> for the text content. The lack of standars for XML to JSON conversion leads developers to choose several property names for the text content of XML <code>Element</code> nodes which contain also other child nodes. Sometimes it is used a property called <code>$</code>. Other times it is used a property called <code>#text</code> (a name like this wouldn't be a good choice, since the text content of a node can be parsed into a non-string value from our algorithms during the conversion). In the algorithms proposed here you can easily change this name, depending on your needs.</p>
<p>The choice of using a <code>true</code> value instead of a <code>null</code> value to represent empty nodes is due to the fact that <em>when in an XML document there is an empty node the reason is often to express a <code>Boolean</code> content</em>, as in this case:</p>
<pre class="brush: xml">&lt;car&gt;
  &lt;type&gt;Ferrari&lt;/type&gt;
  &lt;bought /&gt;
&lt;/car&gt;
</pre>
<p>If the value were <code>null</code> it would be more cumbersome to launch a code like this:</p>
<pre class="brush: js">if (myObject.car.bought) {
  // do something
}
</pre>
<div class="note"><strong>Note:</strong> According to our <a class="internal" href="#JXON_algorithm_3" title="Go to JXON algorithm #3">third algorithm</a> and our <a class="internal" href="#JXON_algorithm_4" title="Go to JXON algorithm #4">fourth algorithm</a>, just <code>Text</code> nodes or <code>CDATASection</code> nodes which contain nothing but white spaces (precisely: <code>/^\s+$/</code>) are parsed as <code>null</code>.</div>
<p>The <a class="internal" href="#JXON_algorithm_4" title="Go to JXON algorithm #4">fourth algorithm</a> represents <em>a special case of conversion</em>. As you can see, <strong>the generated JavaScript Object tree is not <a class="internal" href="/en/JavaScript/Reference/Global_Objects/JSON/stringify" title="en/JavaScript/Reference/Global_Objects/JSON/stringify">stringifyable</a></strong>. It is very practical for internal JavaScript access, but don't use it if you want to transfer the tree via JSON string (as for <code><a class="internal" href="/en/DOM/Worker" title="en/DOM/Worker">Worker</a></code> messages, for example).</p>
<p>We choosed to <strong>ignore nodes which have a prefix</strong> (for example: <code>&lt;ding:dong&gt;binnen&lt;/ding:dong&gt;</code>), due to their special case. You can include them removing the string <code>&amp;&amp; !oNode.prefix</code> from our algorithms (the whole tag will become the property name: <code>{ "ding:dong": "binnen" }</code>).</p>
<p>An important consideration is that, using the third or the fourth algorithm, an XML Document can be used to create any type of Javascript object. For example, If you want to create an object like the following:</p>
<pre class="brush: js">{
  "bool": true,
  "array": ["Cinema", "Hot dogs", false],
  "object": {
    "nickname": "Jack",
    "registration_date": new Date(1995, 11, 25),
    "privileged_user": true
  },
  "num": 99,
  "text": "Hello World!"
}
</pre>
<p>you must just create an XML document with the following structure:</p>
<pre class="brush: xml">&lt;bool&gt;true&lt;/bool&gt;
&lt;array&gt;Cinema&lt;/array&gt;
&lt;array&gt;Hot dogs&lt;/array&gt;
&lt;array&gt;false&lt;/array&gt;
&lt;object&gt;
  &lt;nickname&gt;Jack&lt;/nickname&gt;
  &lt;registration_date&gt;Dec 25, 1995&lt;/registration_date&gt;
  &lt;privileged_user /&gt;
&lt;/object&gt;
&lt;num&gt;99&lt;/num&gt;
&lt;text&gt;Hello World!&lt;/text&gt;
</pre>
<p>This example also shows how <em>the ideal JXON document is an XML document designed specifically to be converted in JSON format</em>, though our algorithms work fine with any kind of XML document.</p>
<h2 id="JXON_object">Appendix: a complete, bidirectional, JXON library</h2>
<p>Now we can create a more complete, bidirectional, JXON library based on <strong>all</strong> our algorithms. Its usage is modelled on the <a class="internal" href="/en/JavaScript/Reference/Global_Objects/JSON" title="en/JavaScript/Reference/Global_Objects/JSON"><code>JSON</code></a> native object.</p>
<pre class="brush: js">const JXON = new (function () {
  const
    sValueProp = "keyValue", sAttributesProp = "keyAttributes", sAttrPref = "@", /* you can customize these values */
    aCache = [], rIsNull = /^\s*$/, rIsBool = /^(?:true|false)$/i;

  function parseText (sValue) {
    if (rIsNull.test(sValue)) { return null; }
    if (rIsBool.test(sValue)) { return sValue.toLowerCase() === "true"; }
    if (isFinite(sValue)) { return parseFloat(sValue); }
    if (isFinite(Date.parse(sValue))) { return new Date(sValue); }
    return sValue;
  }

  function objectify (vValue) {
    return vValue === null ? {} : (vValue instanceof Object ? vValue : new vValue.constructor(vValue));
  }

  function createObjTree (oParentNode, nVerb, bFreeze, bNesteAttr) {
    const
      nLevelStart = aCache.length, bChildren = oParentNode.hasChildNodes(),
      bAttributes = oParentNode.hasAttributes(), bHighVerb = Boolean(nVerb &amp; 2);

    var
      sProp, vContent, nLength = 0, sCollectedTxt = "",
      vResult = bHighVerb ? {} : /* put here the default value for empty nodes: */ true;

    if (bChildren) {
      for (var oNode, nChildId = 0; nChildId &lt; oParentNode.childNodes.length; nChildId++) {
        oNode = oParentNode.childNodes.item(nChildId);
        if (oNode.nodeType === 4) { sCollectedTxt += oNode.nodeValue; } /* nodeType is "CDATASection" (4) */
        else if (oNode.nodeType === 3) { sCollectedTxt += oNode.nodeValue.trim(); } /* nodeType is "Text" (3) */
        else if (oNode.nodeType === 1 &amp;&amp; !oNode.prefix) { aCache.push(oNode); } /* nodeType is "Element" (1) */
      }
    }

    const nLevelEnd = aCache.length, vBuiltVal = parseText(sCollectedTxt);

    if (!bHighVerb &amp;&amp; (bChildren || bAttributes)) { vResult = nVerb === 0 ? objectify(vBuiltVal) : {}; }

    for (var nElId = nLevelStart; nElId &lt; nLevelEnd; nElId++) {
      sProp = aCache[nElId].nodeName.toLowerCase();
      vContent = createObjTree(aCache[nElId], nVerb, bFreeze, bNesteAttr);
      if (vResult.hasOwnProperty(sProp)) {
        if (vResult[sProp].constructor !== Array) { vResult[sProp] = [vResult[sProp]]; }
        vResult[sProp].push(vContent);
      } else {
        vResult[sProp] = vContent;
        nLength++;
      }
    }

    if (bAttributes) {
      const
        nAttrLen = oParentNode.attributes.length,
        sAPrefix = bNesteAttr ? "" : sAttrPref, oAttrParent = bNesteAttr ? {} : vResult;

      for (var oAttrib, nAttrib = 0; nAttrib &lt; nAttrLen; nLength++, nAttrib++) {
        oAttrib = oParentNode.attributes.item(nAttrib);
        oAttrParent[sAPrefix + oAttrib.nodeName.toLowerCase()] = parseText(oAttrib.nodeValue.trim());
      }

      if (bNesteAttr) {
        if (bFreeze) { Object.freeze(oAttrParent); }
        vResult[sAttributesProp] = oAttrParent;
        nLength -= nAttrLen - 1;
      }
    }

    if (nVerb === 3 || (nVerb === 2 || nVerb === 1 &amp;&amp; nLength &gt; 0) &amp;&amp; sCollectedTxt) {
      vResult[sValueProp] = vBuiltVal;
    } else if (!bHighVerb &amp;&amp; nLength === 0 &amp;&amp; sCollectedTxt) {
      vResult = vBuiltVal;
    }

    if (bFreeze &amp;&amp; (bHighVerb || nLength &gt; 0)) { Object.freeze(vResult); }

    aCache.length = nLevelStart;

    return vResult;
  }

  function loadObjTree (oXMLDoc, oParentEl, oParentObj) {
    var vValue, oChild;

    if (oParentObj instanceof String || oParentObj instanceof Number || oParentObj instanceof Boolean) {
      oParentEl.appendChild(oXMLDoc.createTextNode(oParentObj.toString())); /* verbosity level is 0 */
    } else if (oParentObj.constructor === Date) {
      oParentEl.appendChild(oXMLDoc.createTextNode(oParentObj.toGMTString()));    
    }

    for (var sName in oParentObj) {
      if (isFinite(sName)) { continue; } /* verbosity level is 0 */
      vValue = oParentObj[sName];
      if (sName === sValueProp) {
        if (vValue !== null &amp;&amp; vValue !== true) { oParentEl.appendChild(oXMLDoc.createTextNode(vValue.constructor === Date ? vValue.toGMTString() : String(vValue))); }
      } else if (sName === sAttributesProp) { /* verbosity level is 3 */
        for (var sAttrib in vValue) { oParentEl.setAttribute(sAttrib, vValue[sAttrib]); }
      } else if (sName.charAt(0) === sAttrPref) {
        oParentEl.setAttribute(sName.slice(1), vValue);
      } else if (vValue.constructor === Array) {
        for (var nItem = 0; nItem &lt; vValue.length; nItem++) {
          oChild = oXMLDoc.createElement(sName);
          loadObjTree(oXMLDoc, oChild, vValue[nItem]);
          oParentEl.appendChild(oChild);
        }
      } else {
        oChild = oXMLDoc.createElement(sName);
        if (vValue instanceof Object) {
          loadObjTree(oXMLDoc, oChild, vValue);
        } else if (vValue !== null &amp;&amp; vValue !== true) {
          oChild.appendChild(oXMLDoc.createTextNode(vValue.toString()));
        }
        oParentEl.appendChild(oChild);
        }
    }
  }

  this.build = function (oXMLParent, nVerbosity /* optional */, bFreeze /* optional */, bNesteAttributes /* optional */) {
    const _nVerb = arguments.length &gt; 1 &amp;&amp; typeof nVerbosity === "number" ? nVerbosity &amp; 3 : /* put here the default verbosity level: */ 1;
    return createObjTree(oXMLParent, _nVerb, bFreeze || false, arguments.length &gt; 3 ? bNesteAttributes : _nVerb === 3);    
  };

  this.unbuild = function (oJSONData) {    
    const oNewDoc = document.implementation.createDocument("", "", null);
    loadObjTree(oNewDoc, oNewDoc, oJSONData);
    return oNewDoc;
  };
})();


var myObject = JXON.build(doc);
// we got our javascript object! try: alert(JSON.stringify(myObject));

var newDoc = JXON.unbuild(myObject);
// we got our Document instance! try: alert((new XMLSerializer()).serializeToString(newDoc));
</pre>
<h3 name="Syntax">Usage</h3>
<h4 name="Syntax">Syntax</h4>
<p><code>JXON.build(<em>document</em>[, <em>verbosity</em>[, <em>freeze</em>[, <em>nesteAttributes</em>]]])</code></p>
<h4>Description</h4>
<p>Returns a JavaScript Object based on the given XML Document.</p>
<h4 name="Parameters">Parameters</h4>
<dl> <dt><code>document</code></dt> <dd>The XML document to be converted into JSON format.</dd> <dt><code>verbosity</code></dt> <dd>The verbosity level of conversion (optional), from <code>0</code> to <code>3</code>. It is almost equivalent to our algorithms from <a class="internal" href="#JXON_algorithm_4" title="Go to JXON algorithm #4">#4</a> to <a class="internal" href="#JXON_algorithm_1" title="Go to JXON algorithm #1">#1</a> (default value is <code>1</code>, which is equivalent to the <a class="internal" href="#JXON_algorithm_3" title="Go to JXON algorithm #3">algorithm #3</a>).</dd> <dt><code>freeze</code></dt> <dd>A boolean (optional) expressing whether the created object must be <a class="internal" href="/en/JavaScript/Reference/Global_Objects/Object/freeze" title="en/JavaScript/Reference/Global_Objects/Object/freeze">freezed</a> or not (default value is <code>false</code>).</dd> <dt><code>nesteAttributes</code></dt> <dd>A boolean (optional) expressing whether the the attributes must be nested into a child-object named <code>keyAttributes</code> or not (default value is <code>false</code> for verbosity levels from <code>0</code> to <code>2</code>; <code>true</code> for verbosity level <code>3</code>).</dd>
</dl>
<h4 name="Syntax">Syntax</h4>
<p><code>JXON.unbuild(<em>JSONData</em>)</code></p>
<h4>Description</h4>
<p>Returns an XML Document based on the given JavaScript Object.</p>
<h4 name="Parameters">Parameters</h4>
<dl> <dt><code>JSONData</code></dt> <dd>The JavaScript Object from which you want to create your XML Document.</dd>
</dl>
<h3>About this library</h3>
<p>The <code>JXON.build()</code> method summarizes all our four ways of conversion. The result is therefore the same of our four algorithms, depending on the level of verbosity utilised. The only difference is that the <strong>optional properties and methods of the <a class="internal" href="#JXON_algorithm_1" title="Go to JXON algorithm #1">first algorithm</a> (verbosity level: 3) are not included</strong>.</p>
<p>The <code>JXON.unbuild()</code> method utilises our <a class="internal" href="#JXON_reverse_algorithms" title="Reverse algorithms">reverse algorithm</a>.</p>
<p>Therefore, all <a class="internal" href="#JXON_Considerations" title="Code considerations">code considerations</a> remain the same.</p>
<h2>Resources</h2>
<ul> <li><a class="external" href="http://code.google.com/p/xml2json-xslt/wiki/TransformingRules" title="TransformingRules – xml2json-xslt">The Parker Convention</a></li> <li><a class="external" href="http://badgerfish.ning.com/" title="BadgerFish convention">The BadgerFish Convention</a></li> <li><a class="external" href="http://www.balisage.net/Proceedings/vol7/html/Lee01/BalisageVol7-Lee01.html" title="JXON: an Architecture for Schema and Annotation Driven JSON/XML Bidirectional Transformations – Balisage: The Markup Conference 2011">JXON: an Architecture for Schema and Annotation Driven JSON/XML Bidirectional Transformations</a></li> <li><a class="external" href="http://dinogambone.com/2012/jxon-a-simple-way-to-keep-xml-out-of-your-life/" title="JXON – A simple way to keep XML out of your life – Dino Gambone's blog">JXON – A simple way to keep XML out of your life – Dino Gambone's blog</a></li> <li><a class="external" href="http://webreflection.blogspot.it/2008/07/jxon-lossless-javascript-to-xml-object.html" title="Web Reflection: JXON – Lossless JavaScript to XML Object Notation convertion">Web Reflection: JXON – Lossless JavaScript to XML Object Notation convertion</a></li>
</ul>
<h2>See also</h2>
<ul> <li><a class="internal" href="/en/XML" title="en/XML">XML</a></li> <li><a class="internal" href="/en/JSON" title="en/JSON">JSON</a></li> <li><a class="internal" href="/en/XPath" title="en/JXON">XPath</a></li> <li><a class="internal" href="/en/Parsing_and_serializing_XML" title="en/Parsing_and_serializing_XML">Parsing and serializing XML</a></li> <li><a class="internal" href="/en/DOM/XMLHttpRequest" title="en/XMLHttpRequest">XMLHttpRequest</a></li>
</ul>
Revert to this revision