diff options
author | Peter Bengtsson <mail@peterbe.com> | 2020-12-08 14:40:17 -0500 |
---|---|---|
committer | Peter Bengtsson <mail@peterbe.com> | 2020-12-08 14:40:17 -0500 |
commit | 33058f2b292b3a581333bdfb21b8f671898c5060 (patch) | |
tree | 51c3e392513ec574331b2d3f85c394445ea803c6 /files/ja/jxon | |
parent | 8b66d724f7caf0157093fb09cfec8fbd0c6ad50a (diff) | |
download | translated-content-33058f2b292b3a581333bdfb21b8f671898c5060.tar.gz translated-content-33058f2b292b3a581333bdfb21b8f671898c5060.tar.bz2 translated-content-33058f2b292b3a581333bdfb21b8f671898c5060.zip |
initial commit
Diffstat (limited to 'files/ja/jxon')
-rw-r--r-- | files/ja/jxon/index.html | 1483 |
1 files changed, 1483 insertions, 0 deletions
diff --git a/files/ja/jxon/index.html b/files/ja/jxon/index.html new file mode 100644 index 0000000000..e229e1193c --- /dev/null +++ b/files/ja/jxon/index.html @@ -0,0 +1,1483 @@ +--- +title: JXON +slug: JXON +translation_of: Archive/JXON +--- +<p><strong>JXON</strong> (<strong>J</strong>avaScript <strong>X</strong>ML <strong>O</strong>bject <strong>N</strong>otationの略)は<a href="/en/XML" title="en/XML">XML</a>を使ってJavaScriptオブジェクトを生成する一般的な名称です。 There are no real standards for this conversion, but <a 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 read 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> + +<p>In this article we will show how to convert a parsed XML <a href="/ja/docs/Web/API/Document" title="Document インターフェイスはブラウザーに読み込まれたウェブページを表し、DOM ツリー であるウェブページのコンテンツへのエントリーポイントとして働きます。"><code>document</code></a> (i.e. an instance of <a 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 href="/en/JavaScript/Reference/Global_Objects/Object" title="en/JavaScript/Reference/Global_Objects/Object"><code>Object</code></a>) and viceversa, with some different algorithms. It could be useful to read the <a href="/en/XML_Introduction" title="en/XML_Introduction">XML introduction article</a> first.</p> + +<p>If you want <strong>a complete bidirectional JXON library</strong> (modelled on the <a href="/en/JavaScript/Reference/Global_Objects/JSON" title="en/JavaScript/Reference/Global_Objects/JSON"><code>JSON</code></a> global object), skip to the <a href="#Appendix.3A_a_complete.2C_bidirectional.2C_JXON_library" title="A complete JXON library">dedicated paragraph</a> (but please read the <a href="#const_compatibility" title="#const_compatibility">note about the <code>const</code> statement compatibility</a>).</p> + +<div class="note"><strong>Note:</strong> If you are interested to address only some parts of an XML document (and are not starting in JavaScript/JSON for templating purposes), use <a href="/en/XPath" title="en/XPath">XPath</a> instead of converting the whole document into JSON.</div> + +<h2 id="Conversion_snippets">Conversion snippets</h2> + +<p>Now imagine you have this sample XML document:</p> + +<h5 id="example.xml">example.xml</h5> + +<pre class="brush: 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> +</pre> + +<p>First, create a DOM tree like the previous example as described in the <a 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 href="/ja/docs/Web/API/XMLHttpRequest" title="XMLHttpRequest は、クライアントとサーバーの間でデータを伝送するための機能をクライアント側で提供する API です。ページ全体を再読み込みすることなく、URL からデータを読み出す簡単な方法を提供します。この API によって、ユーザの作業を中断させることなく Web ページの一部を更新することができます。"><code>XMLHttpRequest</code></a>, skip to the next paragraph.</p> + +<div class="note"><strong>Note:</strong> If you are using an instance of <a href="/en-US/docs/DOM/XMLHttpRequest" title="/en-US/docs/DOM/XMLHttpRequest"><code>XMLHttpRequest</code></a> in order to retrieve your XML file, please use the <code>yourRequest.responseXML</code> property to get a <em>parsed</em> XML document. Don't use <code>yourRequest.responseText</code>!</div> + +<p>The algorithms proposed here (see: <a href="#Algorithm_.231.3A_a_verbose_way" title="Go to JXON algorithm #1">#1</a>, <a href="#Algorithm_.232.3A_a_less_verbose_way" title="Go to JXON algorithm #2">#2</a>, <a href="#Algorithm_.233.3A_a_synthetic_technique" title="Go to JXON algorithm #3">#3</a>, <a href="#Algorithm_.234.3A_a_very_minimalist_way" title="Go to JXON algorithm #4">#4</a>) will consider only the following types of nodes and their attributes:</p> + +<ol> + <li><a href="/ja/docs/Web/API/Document" title="Document インターフェイスはブラウザーに読み込まれたウェブページを表し、DOM ツリー であるウェブページのコンテンツへのエントリーポイントとして働きます。"><code>Document</code></a> (only as function argument),</li> + <li><a href="/ja/docs/Web/API/DocumentFragment" title="DocumentFragment インタフェースは、親ノードの無い最小限度の文書オブジェクトを表します。整形式の、または潜在的に整形式でない XML の 断片を保持するために Document の軽量版として使われます。"><code>DocumentFragment</code></a> (only as function argument),</li> + <li><a href="/ja/docs/Web/API/Element" title="Element インターフェイスは Document の一部分を表現します。このインターフェイスは個々の種類の要素に共通するメソッドとプロパティを記述するものです。特異な挙動は Element から継承した特異なインターフェイスで記述します。"><code>Element</code></a>,</li> + <li><a href="/ja/docs/Web/API/Text" title="Text インターフェイスは、Element または Attr のテキストコンテンツを表します。要素の内部にマークアップが含まれていない場合、その要素は要素内のテキストを包含する Text を実装する子を 1 つ持ちます。一方要素がマークアップを含む場合は情報アイテムと、要素の子を構成する Text ノードに解析されます。"><code>Text</code></a> (never as function argument),</li> + <li><a href="/ja/docs/Web/API/CDATASection" title="CDATA セクション内では、通常の文字として XML 内に記述する場合に実態参照として記述する必要がある &lt; や &amp; のように記述する必要がある)を、エスケープ無しでそのまま記述する事ができます。"><code>CDATASection</code></a> (never as function argument),</li> + <li><a href="/ja/docs/Web/API/Attr" title="この型は、DOM 要素の属性をオブジェクトとして提供します。ほとんどの DOM メソッドは、この属性を文字列として直接取得するでしょう (例: Element.getAttribute())。しかし、特定の関数 (例: Element.getAttributeNode()) やイテレーションを表すものには Attr 型を付与します。"><code>Attr</code></a> (never as function argument).</li> +</ol> + +<p>This is a good and <strong>standardized</strong> compromise for a JavaScript usage, since all of the information of an XML Document is contained in these node types. All other information (like processing instructions, schemas, comments, etc.) will be lost. This type of algorithm is still considered <strong>lossless</strong>, since what is lost is <strong>meta-information</strong> and not <strong>information</strong>.</p> + +<p>In order to avoid conflicts, the representation of nodes and attributes names is <strong>case insensitive</strong> (always rendered in <strong>lower case</strong>), so objects' local property names set using JavaScript must always have some kind of capitalization (that is, at least one capital letter somewhere in their names), as you can see below.</p> + +<p>The following algorithms are somewhat based on the <a href="#The_Parker_Convention" title="The Parker Convention">Parker convention, version 0.4</a>, which prescribes the <strong>transformation of <a href="/en/DOM/Node.nodeName" title="en/DOM/Node.nodeName">tags names</a> into <a href="/en/JavaScript/Guide/Working_with_Objects#Objects_and_properties" title="en/Core_JavaScript_1.5_Guide/Working_with_Objects#Objects_and_properties">object properties names</a></strong> and the <strong>recognition of the <a href="/en/JavaScript/Reference/Operators/typeof" title="en/JavaScript/Reference/Operators/typeof"><code>typeof</code></a></strong> of all the collected <a href="/en/DOM/Node.nodeValue" title="en/DOM/Node.nodeValue"><code>text content</code></a> of each tag (plain text parsing); but <a href="#Code_considerations" title="Code considerations">with some differences</a> (so, one can say that we follow <em>a our convention</em>). Moreover, <strong>all algorithms are equally lossless for the contemplated nodes</strong>.</p> + +<p>We consider <strong><a href="#Algorithm_.233.3A_a_synthetic_technique" title="Go to JXON algorithm #3">the third algorithm</a> as the most representative and practical JXON parsing algorithm</strong>.</p> + +<p>Now let's serialize <code>doc</code> — the DOM tree — to a JavaScript Object Tree (you can read more about <a href="/en/JavaScript/Guide/Working_with_Objects" title="Working with Objects">working with Objects</a> and <a 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="アルゴリズム_1_a_verbose_way">アルゴリズム #1: a verbose way</h3> + +<p>この単純で再帰的なコンストラクタはXML DOM treeをJavaScript Object treeに変換します。 それぞれの要素のテキストコンテンツは要素の中の<code>keyValueプロパティの値に格納されています。もし属性(nodeAttributes)が存在する場合</code>、<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.</p> + +<pre class="brush: js">/*\ +|*| +|*| JXON Snippet #1 - Mozilla Developer Network +|*| +|*| https://developer.mozilla.org/en-US/docs/JXON +|*| +\*/ + +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 JXONTree (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 JXONTree(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.name.toLowerCase()] = parseText(oAttrib.value.trim()); + } + } + /* + * Optional properties... + + this.keyLength = nLength; + this.attributesLength = nAttrLen; + // this.DOMNode = oXMLParent; + + */ + + /* Object.freeze(this); */ +} + +/* +* Optional methods... Uncomment the optional properties first! + +JXONTree.prototype.valueOf = function () { return this.keyValue; }; +JXONTree.prototype.toString = function () { return String(this.keyValue); }; +JXONTree.prototype.getItem = function (nItem) { + if (nLength === 0) { return null; } + var nCount = 0; + for (var sKey in this) { if (nCount === nItem) { return this[sKey]; } nCount++; } + return null; +}; +JXONTree.prototype.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; +}; +JXONTree.prototype.hasChildren = function () { return this.keyLength > 0; }; + +*/ + +var myObject = new JXONTree(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 an XML document), uncomment the string: <code>/* Object.freeze(this); */</code>. The <code><a 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 href="#example.xml" title="Go to the sample XML document">our example</a> becomes:</p> + +<pre class="brush: js">{ + "catalog": { + "product": { + "catalog_item": [{ + "item_number": { + "keyValue": "QWZ5671" + }, + "price": { + "keyValue": 39.95 + }, + "size": [{ + "color_swatch": [{ + "keyValue": "Red", + "keyAttributes": { + "image": "red_cardigan.jpg" + } + }, { + "keyValue": "Burgundy", + "keyAttributes": { + "image": "burgundy_cardigan.jpg" + } + }], + "keyValue": null, + "keyAttributes": { + "description": "Medium" + } + }, { + "color_swatch": [{ + "keyValue": "Red", + "keyAttributes": { + "image": "red_cardigan.jpg" + } + }, { + "keyValue": "Burgundy", + "keyAttributes": { + "image": "burgundy_cardigan.jpg" + } + }], + "purchased": { + "keyValue": null + }, + "keyValue": null, + "keyAttributes": { + "description": "Large" + } + }], + "keyValue": null, + "keyAttributes": { + "gender": "Men's" + } + }, { + "item_number": { + "keyValue": "RRX9856" + }, + "discount_until": { + "keyValue": new Date(1995, 11, 25) + }, + "price": { + "keyValue": 42.5 + }, + "size": { + "color_swatch": { + "keyValue": "Black", + "keyAttributes": { + "image": "black_cardigan.jpg" + } + }, + "keyValue": null, + "keyAttributes": { + "description": "Medium" + } + }, + "keyValue": null, + "keyAttributes": { + "gender": "Women's" + } + }], + "keyValue": null, + "keyAttributes": { + "description": "Cardigan Sweater" + } + }, + "script": { + "keyValue": "function matchwo(a,b) {\n if (a < b && a < 0) { return 1; }\n else { return 0; }\n}", + "keyAttributes": { + "type": "text/javascript" + } + }, + "keyValue": null + }, + "keyValue": null +} +</pre> + +<p>This is a recommanded technique if you don't know the structure of the XML document.</p> + +<h3 id="Algorithm_2_a_less_verbose_way">Algorithm #2: a less verbose way</h3> + +<p>Here is another, simpler, conversion method, in which <code>nodeAttributes</code> are listed under the same object of child nodes but have the “@” prefix (as suggested by the <a href="http://badgerfish.ning.com/" title="BadgerFish convention">BadgerFish Convention</a>). 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">/*\ +|*| +|*| JXON Snippet #2 - Mozilla Developer Network +|*| +|*| https://developer.mozilla.org/en-US/docs/JXON +|*| +\*/ + +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 JXONTree (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 JXONTree(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.name.toLowerCase()] = parseText(oAttrib.value.trim()); + } + } + /* Object.freeze(this); */ +} + +var myObject = new JXONTree(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 an XML document), uncomment the string: <code>/* Object.freeze(this); */</code>. The <code><a 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 href="#example.xml" title="Go to the sample XML document">our example</a> becomes:</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 < b && a < 0) { return 1; }\n else { return 0; }\n}", + "@type": "text/javascript" + } + } +} +</pre> + +<p>This is a possible technique to use if you partially know the structure of the XML document.</p> + +<h3 id="Algorithm_3_a_synthetic_technique">Algorithm #3: a synthetic technique</h3> + +<p>Here is another method of conversion. This algorithm is the closest to the <a 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 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, <code>CDATASection</code> nodes or <code>Attr</code> nodes) have the default value <code>true</code> (see the <a href="#Code_considerations" title="Code considerations">Code considerations</a>). Also, this time we use a function instead of a constructor. The function's argument can be the entire XML <a href="/ja/docs/Web/API/Document" title="Document インターフェイスはブラウザーに読み込まれたウェブページを表し、DOM ツリー であるウェブページのコンテンツへのエントリーポイントとして働きます。"><code>Document</code></a>, a <a href="/ja/docs/Web/API/DocumentFragment" title="DocumentFragment インタフェースは、親ノードの無い最小限度の文書オブジェクトを表します。整形式の、または潜在的に整形式でない XML の 断片を保持するために Document の軽量版として使われます。"><code>DocumentFragment</code></a>, or simply an <a href="/ja/docs/Web/API/Element" title="Element インターフェイスは Document の一部分を表現します。このインターフェイスは個々の種類の要素に共通するメソッドとプロパティを記述するものです。特異な挙動は Element から継承した特異なインターフェイスで記述します。"><code>Element</code></a> node within it. <code>nodeAttributes</code> have the “@” prefix, as suggested by the <a href="http://badgerfish.ning.com/" title="BadgerFish convention">BadgerFish Convention</a>. <strong>In many cases, this is the most practical conversion method</strong>.</p> + +<pre class="brush: js">/*\ +|*| +|*| JXON Snippet #3 - Mozilla Developer Network +|*| +|*| https://developer.mozilla.org/en-US/docs/JXON +|*| +\*/ + +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 getJXONTree (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.name.toLowerCase()] = parseText(oAttrib.value.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 = getJXONTree(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 = getJXONTree(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 an XML document), uncomment the string: <code>/* if (nLength > 0) { Object.freeze(vResult); } */</code>. The <code><a 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 href="#example.xml" title="Go to the sample XML document">our example</a> becomes:</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 < b && a < 0) { return 1; }\n else { return 0; }\n}" + } + } +} +</pre> + +<p>This is a recommended technique if you know the structure of the XML document.</p> + +<h3 id="Algorithm_4_a_very_minimalist_way">Algorithm #4: a very minimalist way</h3> + +<p>The following is another possible way to do the conversion. It is very close to the <a href="#The_Parker_Convention" title="The Parker Convention">Parker convention</a>, too. With this algorithm, all <a href="/ja/docs/Web/API/Element" title="Element インターフェイスは Document の一部分を表現します。このインターフェイスは個々の種類の要素に共通するメソッドとプロパティを記述するものです。特異な挙動は Element から継承した特異なインターフェイスで記述します。"><code>Element</code></a> nodes that contain other child <a href="/ja/docs/Web/API/Element" title="Element インターフェイスは Document の一部分を表現します。このインターフェイスは個々の種類の要素に共通するメソッドとプロパティを記述するものです。特異な挙動は Element から継承した特異なインターフェイスで記述します。"><code>Element</code></a>, <a href="/ja/docs/Web/API/Text" title="Text インターフェイスは、Element または Attr のテキストコンテンツを表します。要素の内部にマークアップが含まれていない場合、その要素は要素内のテキストを包含する Text を実装する子を 1 つ持ちます。一方要素がマークアップを含む場合は情報アイテムと、要素の子を構成する Text ノードに解析されます。"><code>Text</code></a>, or <a href="/ja/docs/Web/API/CDATASection" title="CDATA セクション内では、通常の文字として XML 内に記述する場合に実態参照として記述する必要がある &lt; や &amp; のように記述する必要がある)を、エスケープ無しでそのまま記述する事ができます。"><code>CDATASection</code></a> 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"><employee type="usher">John Smith</employee> +<manager>Lisa Carlucci</manager> +</pre> + +<p>becomes</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 href="/en/JavaScript/Reference/Global_Objects/JSON/stringify" title="en/JavaScript/Reference/Global_Objects/JSON/stringify">stringifyable</a></strong> (see the <a href="#Code_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, <code>CDATASection</code> nodes or <code>Attr</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. <code>nodeAttributes</code> have the “@” prefix, as suggested by the <a href="http://badgerfish.ning.com/" title="BadgerFish convention">BadgerFish Convention</a>.</p> + +<pre class="brush: js">/*\ +|*| +|*| JXON Snippet #4 - Mozilla Developer Network +|*| +|*| https://developer.mozilla.org/en-US/docs/JXON +|*| +\*/ + +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 getJXONTree (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.name.toLowerCase()] = parseText(oAttrib.value.trim()); + } + } else if (nLevelEnd > nLevelStart) { vResult = objectify(vBuiltVal); } + + for (var nElId = nLevelStart; nElId < nLevelEnd; nElId++) { + sProp = aTmpEls[nElId].nodeName.toLowerCase(); + vContent = getJXONTree(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 = getJXONTree(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 an XML document), uncomment the string: <code>/* else { Object.freeze(vResult); } */</code>. The <code><a 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>This is a possible technique if you know the structure of the XML document.</p> + +<h3 id="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 single method represents the inversion of all our algorithms.</p> + +<pre class="brush: js">/*\ +|*| +|*| JXON Snippet #5 - Mozilla Developer Network +|*| +|*| https://developer.mozilla.org/en-US/docs/JXON +|*| +\*/ + +function createXML (oObjTree) { + function loadObjTree (oParentEl, oParentObj) { + var vValue, oChild; + if (oParentObj.constructor === String || oParentObj.constructor === Number || oParentObj.constructor === Boolean) { + oParentEl.appendChild(oNewDoc.createTextNode(oParentObj.toString())); /* verbosity level is 0 or 1 */ + if (oParentObj === oParentObj.valueOf()) { return; } + } 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, oObjTree); + 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 they exist, are converted into <a href="/en/JavaScript/Reference/Global_Objects/String" title="String">Strings</a> through the <a href="/en/JavaScript/Reference/Global_Objects/Date/toGMTString" title="toGMTString"><code>toGMTString()</code></a> 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 href="#Code_considerations" title="Code considerations">Code considerations</a>).</div> + +<p>This is a good solution if you want to automate the creation of an XML document. It is a bad choice, however, if you want to re-build an XML document previously converted into JSON. Although <strong>the bidirectional conversion is very faithful</strong> (except for <a href="/ja/docs/Web/API/CDATASection" title="CDATA セクション内では、通常の文字として XML 内に記述する場合に実態参照として記述する必要がある &lt; や &amp; のように記述する必要がある)を、エスケープ無しでそのまま記述する事ができます。"><code>CDATASection</code></a> nodes, which will be converted into <a href="/ja/docs/Web/API/Text" title="Text インターフェイスは、Element または Attr のテキストコンテンツを表します。要素の内部にマークアップが含まれていない場合、その要素は要素内のテキストを包含する Text を実装する子を 1 つ持ちます。一方要素がマークアップを含む場合は情報アイテムと、要素の子を構成する Text ノードに解析されます。"><code>Text</code></a> nodes), the process is unnecessarily costly. In fact, if your 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 href="/en/JSON" title="en/JSON">JSON</a> (often called "JXON algorithms") are more or less freely based on the Parker Convention (especially regarding the transformation of <a href="/en/DOM/Node.nodeName" title="en/DOM/Node.nodeName">tags names</a> into <a href="/en/JavaScript/Guide/Working_with_Objects#Objects_and_properties" title="en/Core_JavaScript_1.5_Guide/Working_with_Objects#Objects_and_properties">object properties names</a>, the recognition of the <a href="/en/JavaScript/Reference/Operators/typeof" title="en/JavaScript/Reference/Operators/typeof"><code>typeof</code></a> of all the collected <a href="/en/DOM/Node.nodeValue" title="en/DOM/Node.nodeValue"><code>text content</code></a> of each tag and the absorption of solitary <code>Text</code> and/or <code>CDATASection</code> nodes into primitive values). It is called “Parker Convention” in opposition to “BadgerFish Convention”, after the comic Parker & Badger by Cuadrado. See also: <a 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 href="http://code.google.com/p/xml2json-xslt/wiki/TransformingRules" title="TransformingRules – xml2json-xslt">TransformingRules</a>” of the <a 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 href="/en/JSON" title="en/JSON">JSON</a> from <a href="/en/XSLT" title="en/XSLT">XSLT</a>, so parts of it are futile for JavaScript.</p> + +<div class="note"><strong>Note:</strong> On October 29th, 2013, the World Wide Web Consortium relased <a href="http://www.w3.org/TR/microdata/#json" title="Converting HTML to other formats: JSON – World Wide Web Consortium">in a note</a> on <em>official</em> algorithm for converting <em><a href="/en-US/docs/Web/HTML/Global_attributes#itemid">HTML5 microdata</a></em> to <em><a href="/en/JSON" title="en/JSON">JSON</a></em>. However, <em>HTML microdata</em> <strong>is not</strong> <em>HTML:</em> microdata is a formatted <strong>subset</strong> of HTML.</div> + +<h3 id="Translation_JSON">Translation JSON</h3> + +<ol> + <li> + <p>The root element will be absorbed, for there is only one:</p> + + <pre class="brush: xml"><root>test</root></pre> + + <p>becomes</p> + + <pre class="brush: js">"test" +</pre> + </li> + <li> + <p>Element names become object properties:</p> + + <pre class="brush: xml"><root><name>Xml</name><encoding>ASCII</encoding></root></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"><root><age>12</age><height>1.73</height></root></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"><root><checked>True</checked><answer>FALSE</answer></root></pre> + + <p>becomes</p> + + <pre class="brush: js">{ + "checked": true, + "answer": false +} +</pre> + </li> + <li> + <p>Strings are escaped:</p> + + <pre class="brush: xml"><root>Quote: &quot; New-line: +</root> +</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"><root><nil/><empty></empty></root></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"><root><item>1</item><item>2</item><item>three</item></root> +</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"><root version="1.0">testing<!--comment--><element test="true">1</element></root> +</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"><root xmlns:ding="http://zanstra.com/ding"><ding:dong>binnen</ding:dong></root> +</pre> + + <p>becomes</p> + + <pre class="brush: js">{ "ding:dong" : "binnen" } +</pre> + </li> +</ol> + +<div class="note"><strong>Note:</strong> Our algorithms comply with points 2, 3, 4 and 7. The third and the fourth algorithm comply also with point 6 (but <code>true</code> instead of <code>null</code> – see the <a href="#Code_considerations" title="Code considerations">Code considerations</a>). Point 5 is automatically managed by the JavaScript method <code><a href="/en/JavaScript/Reference/Global_Objects/JSON/stringify" title="en/JavaScript/Reference/Global_Objects/JSON/stringify">JSON.stringify()</a></code>. Regarding point 9, we chose to ignore all nodes which have a prefix; you can include them by removing the string <code>&& !oNode.prefix</code> from our algorithms (see the <a href="#Code_considerations" title="Code considerations">Code considerations</a>).</div> + +<h3 id="Extra_JavaScript_translations">Extra JavaScript translations</h3> + +<p>This is the same as the JSON translation, but with these extras:</p> + +<ol> + <li> + <p>Property names are only escaped when necessary</p> + + <pre class="brush: xml"><root><while>true</while><wend>false</wend><only-if/></root> +</pre> + + <p>becomes</p> + + <pre class="brush: js">{ + "while": true, + wend: false, + "only-if": null +} +</pre> + </li> + <li> + <p>Within a string, closing elements "</" are escaped as "<\/"</p> + + <pre class="brush: xml"><root><![CDATA[<script>alert("YES");</script>]]></root></pre> + + <p>becomes</p> + + <pre class="brush: js">{ script: "<script>alert(\"YES\")<\/script>" } +</pre> + </li> + <li> + <p>Dates are created as new <a href="/en/JavaScript/Reference/Global_Objects/Date" title="Date"><code>Date</code></a> objects</p> + + <pre class="brush: xml"><root>2006-12-25</root></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"><!--testing--><root><test version="1.0">123</test></root> +</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 legible</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 href="/en/JavaScript/Reference/Global_Objects/JSON/stringify" title="en/JavaScript/Reference/Global_Objects/JSON/stringify">JSON.stringify()</a></code>.</div> + +<h2 id="概要">概要</h2> + +<p>Let's take <strong><a href="#Algorithm_.233.3A_a_synthetic_technique" 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 href="#Algorithm_.233.3A_a_synthetic_technique" 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><animal /></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><animal>Deka</animal></code></td> + <td style="background: #e7e5dc; color: #silver;"><code>"animal": "Deka"</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><animal name="Deka" /></code></td> + <td style="background: #f6f6f6; color: #000000;"><code>"animal": {"@name": "Deka"}</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><animal name="Deka">is my cat</animal></code></td> + <td style="background: #e7e5dc; color: #silver;"><code>"animal": { "@name": "Deka", "keyValue": "is my cat" }</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><animal> <dog>Charlie</dog> <cat>Deka</cat> </animal></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><animal> <dog>Charlie</dog> <dog>Mad Max</dog> </animal></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><animal> in my house <dog>Charlie</dog> </animal></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><animal> in my ho <dog>Charlie</dog> use </animal></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="Code_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 standards for XML to JSON conversion leads developers to choose a variety of property names for the text content of XML <a href="/ja/docs/Web/API/Element" title="Element インターフェイスは Document の一部分を表現します。このインターフェイスは個々の種類の要素に共通するメソッドとプロパティを記述するものです。特異な挙動は Element から継承した特異なインターフェイスで記述します。"><code>Element</code></a> nodes that also contain other child nodes. Sometimes a property called <code>$</code> is used. Other times a property called <code>#text</code> is used (however, a name like this isn't a good choice, since the text content of a node can be parsed into a non-string value by 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 <strong>when in an XML document there is an empty node the reason is often to express a<em> <code>Boolean</code></em></strong>, as in this case:</p> + +<pre class="brush: xml"><car> + <type>Ferrari</type> + <bought /> +</car> +</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 href="#Algorithm_.233.3A_a_synthetic_technique" title="Go to JXON algorithm #3">third algorithm</a> and our <a href="#Algorithm_.234.3A_a_very_minimalist_way" title="Go to JXON algorithm #4">fourth algorithm</a>, just <code>CDATASection</code> nodes which contain nothing but white spaces (precisely: <code>/^\s+$/</code>) will be parsed as <code>null</code>.</div> + +<p>The <a href="#Algorithm_.234.3A_a_very_minimalist_way" title="Go to JXON algorithm #4">fourth algorithm</a> represents a <strong>special case of conversion</strong>. As you can see, <strong>the generated JavaScript Object tree is not <a 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 href="/en/DOM/Worker" title="en/DOM/Worker">Worker</a></code> messages, for example).</p> + +<p>We chose to <strong>ignore nodes which have a prefix</strong> (for example: <code><ding:dong>binnen</ding:dong></code>), due to their special case (they are often used in order to represents an <a href="http://www.w3.org/TR/xmlschema-ref/" title="W3C XML Schema Definition Language (XSD): Component Designators">XML Schema</a>, which is <em>meta-information</em> concerning how to organize the <em>information</em> of the document, reserved for the XML parser). You can include them removing the string <code>&& !oNode.prefix</code> from our algorithms (by doing so the whole tag will become the property name: <code>{ "ding:dong": "binnen" }</code>).</p> + +<p>An important consideration is that, when using the <a href="#Algorithm_.233.3A_a_synthetic_technique" title="Go to JXON algorithm #3">third</a> or the <a href="#Algorithm_.234.3A_a_very_minimalist_way" title="Go to JXON algorithm #4">fourth</a> algorithm, an XML <a href="/ja/docs/Web/API/Document" title="Document インターフェイスはブラウザーに読み込まれたウェブページを表し、DOM ツリー であるウェブページのコンテンツへのエントリーポイントとして働きます。"><code>Document</code></a> 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">{ + "myboolean": true, + "myarray": ["Cinema", "Hot dogs", false], + "myobject": { + "nickname": "Jack", + "registration_date": new Date(1995, 11, 25), + "privileged_user": true + }, + "mynumber": 99, + "mytext": "Hello World!" +} +</pre> + +<p>you must just create an XML document with the following structure:</p> + +<pre class="brush: xml"><myboolean>true</myboolean> +<myarray>Cinema</myarray> +<myarray>Hot dogs</myarray> +<myarray>false</myarray> +<myobject> + <nickname>Jack</nickname> + <registration_date>Dec 25, 1995</registration_date> + <privileged_user /> +</myobject> +<mynumber>99</mynumber> +<mytext>Hello World!</mytext> +</pre> + +<p>This example also shows how the ideal JXON document is an XML document designed specifically to be converted in JSON format, though <em>our algorithms work fine with any kind of XML document</em>.</p> + +<div class="note" id="ordering-lossless-note"><strong>Note:</strong> Despite the term JXON suggesting "lossless" conversions, these techniques are not actually lossless if one needs to preserve <strong>ordering of elements</strong>, as is common with many XML dialects (including of course <a href="/en-US/docs/XHTML" title="/en-US/docs/XHTML">XHTML</a>). The ECMAScript standard (JavaScript) indicates that object iteration order is <em>implementation dependent</em>.</div> + +<h2 id="付録_a_complete_bidirectional_JXON_library">付録: a complete, bidirectional, JXON library</h2> + +<p>Now we can create a more complete, bidirectional, JXON library based on <strong>all</strong> our algorithms (see: <a href="#Algorithm_.231.3A_a_verbose_way" title="Go to JXON algorithm #1">#1</a>, <a href="#Algorithm_.232.3A_a_less_verbose_way" title="Go to JXON algorithm #2">#2</a>, <a href="#Algorithm_.233.3A_a_synthetic_technique" title="Go to JXON algorithm #3">#3</a>, <a href="#Algorithm_.234.3A_a_very_minimalist_way" title="Go to JXON algorithm #4">#4</a>, <a href="#Reverse_algorithms" title="Reverse algorithms">reverse</a>). Its usage is modeled on the <a href="/en/JavaScript/Reference/Global_Objects/JSON" title="en/JavaScript/Reference/Global_Objects/JSON"><code>JSON</code></a> native object. <strong>Before implementing it in a working environment, please read the <a href="#const_compatibility" title="#const_compatibility">note about the <code>const</code> statement compatibility</a></strong>.</p> + +<pre class="brush: js"> /*\ + |*| + |*| JXON framework - Copyleft 2011 by Mozilla Developer Network + |*| + |*| Revision #1 - September 5, 2014 + |*| + |*| https://developer.mozilla.org/en-US/docs/JXON + |*| + |*| This framework is released under the GNU Public License, version 3 or later. + |*| http://www.gnu.org/licenses/gpl-3.0-standalone.html + |*| + \*/ + +const JXON = new (function () { + + const + sValProp = "keyValue", sAttrProp = "keyAttributes", sAttrsPref = "@", /* 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 EmptyTree () {} + + EmptyTree.prototype.toString = function () { return "null"; }; + + EmptyTree.prototype.valueOf = function () { return null; }; + + function objectify (vVal) { + return vVal === null ? new EmptyTree() : vVal instanceof Object ? vVal : new vVal.constructor(vVal); + } + + 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, nItem = 0; nItem < oParentNode.childNodes.length; nItem++) { + oNode = oParentNode.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) { 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 ? "" : sAttrsPref, oAttrParent = bNesteAttr ? {} : vResult; + + for (var oAttrib, nAttrib = 0; nAttrib < nAttrLen; nLength++, nAttrib++) { + oAttrib = oParentNode.attributes.item(nAttrib); + oAttrParent[sAPrefix + oAttrib.name.toLowerCase()] = parseText(oAttrib.value.trim()); + } + + if (bNesteAttr) { + if (bFreeze) { Object.freeze(oAttrParent); } + vResult[sAttrProp] = oAttrParent; + nLength -= nAttrLen - 1; + } + + } + + if (nVerb === 3 || (nVerb === 2 || nVerb === 1 && nLength > 0) && sCollectedTxt) { + vResult[sValProp] = 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.constructor === String || oParentObj.constructor === Number || oParentObj.constructor === Boolean) { + oParentEl.appendChild(oXMLDoc.createTextNode(oParentObj.toString())); /* verbosity level is 0 or 1 */ + if (oParentObj === oParentObj.valueOf()) { return; } + } else if (oParentObj.constructor === Date) { + oParentEl.appendChild(oXMLDoc.createTextNode(oParentObj.toGMTString())); + } + + for (var sName in oParentObj) { + vValue = oParentObj[sName]; + if (isFinite(sName) || vValue instanceof Function) { continue; } /* verbosity level is 0 */ + if (sName === sValProp) { + if (vValue !== null && vValue !== true) { oParentEl.appendChild(oXMLDoc.createTextNode(vValue.constructor === Date ? vValue.toGMTString() : String(vValue))); } + } else if (sName === sAttrProp) { /* verbosity level is 3 */ + for (var sAttrib in vValue) { oParentEl.setAttribute(sAttrib, vValue[sAttrib]); } + } else if (sName.charAt(0) === sAttrsPref) { + 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); + } + } + + } + + /* Uncomment the following code if you want to enable the .appendJXON() method for *all* the "element" objects! */ + + /* + + Element.prototype.appendJXON = function (oObjTree) { + loadObjTree(document, this, oObjTree); + return this; + }; + + */ + + this.build = function (oXMLParent, nVerbosity /* optional */, bFreeze /* optional */, bNesteAttributes /* optional */) { + const nVerbMask = arguments.length > 1 && typeof nVerbosity === "number" ? nVerbosity & 3 : /* put here the default verbosity level: */ 1; + return createObjTree(oXMLParent, nVerbMask, bFreeze || false, arguments.length > 3 ? bNesteAttributes : nVerbMask === 3); + }; + + this.unbuild = function (oObjTree, sNamespaceURI /* optional */, sQualifiedName /* optional */, oDocumentType /* optional */) { + const oNewDoc = document.implementation.createDocument(sNamespaceURI || null, sQualifiedName || "", oDocumentType || null); + loadObjTree(oNewDoc, oNewDoc, oObjTree); + return oNewDoc; + }; + +})(); +</pre> + +<div class="note" id="const_compatibility"><strong>Note:</strong> The current implementation of <a href="/en/JavaScript/Reference/Statements/const" title="en/JavaScript/Reference/Statements/const"><code>const</code></a> (constant statement) <strong>is not part of ECMAScript 5</strong>. It is supported in Firefox & Chrome (V8) and partially supported in Opera 9+ and Safari. <strong>It is not supported in Internet Explorer 6-9, or in the preview of Internet Explorer 10</strong>. <a href="/en/JavaScript/Reference/Statements/const" title="en/JavaScript/Reference/Statements/const"><code>const</code></a> is going to be defined by ECMAScript 6, but with different semantics. Similar to variables declared with the <a href="/en/JavaScript/Reference/Statements/let" title="en/JavaScript/Reference/Statements/let"><code>let</code></a> statement, constants declared with <a href="/en/JavaScript/Reference/Statements/const" title="en/JavaScript/Reference/Statements/const"><code>const</code></a> will be block-scoped. <strong>We used it only for didactic purpose. If you want a full browser compatibility of this library, please replace all the <a href="/en/JavaScript/Reference/Statements/const" title="en/JavaScript/Reference/Statements/const"><code>const</code></a> statements with the <a href="/en/JavaScript/Reference/Statements/var" title="en/JavaScript/Reference/Statements/var"><code>var</code></a> statements.</strong></div> + +<h3 id="使い方">使い方</h3> + +<p>The obtained non-native <code>JXON</code> global object will have two methods:</p> + +<table class="fullwidth-table"> + <tbody> + <tr> + <th>Method</th> + <th>Description</th> + </tr> + <tr> + <td><a href="#JXON.build_syntax" title="JXON.build"><code>JXON.build(<em>document</em>[, <em>verbosity</em>[, <em>freeze</em>[, <em>nesteAttributes</em>]]])</code></a></td> + <td>Returns a JavaScript <a href="/en/JavaScript/Reference/Global_Objects/Object" title="en/JavaScript/Reference/Global_Objects/Object"><code>Object</code></a> based on the given XML Document.</td> + </tr> + <tr> + <td><a href="#JXON.unbuild_syntax" title="JXON.unbuild"><code>JXON.unbuild(<em>objTree</em>[, <em>namespaceURI</em>[, <em>qualifiedNameStr</em>[, <em>documentType</em>]]])</code></a></td> + <td>Returns an XML <a href="/ja/docs/Web/API/Document" title="Document インターフェイスはブラウザーに読み込まれたウェブページを表し、DOM ツリー であるウェブページのコンテンツへのエントリーポイントとして働きます。"><code>Document</code></a> based on the given JavaScript <a href="/en/JavaScript/Reference/Global_Objects/Object" title="en/JavaScript/Reference/Global_Objects/Object"><code>Object</code></a>.</td> + </tr> + </tbody> +</table> + +<p>These methods are inverses of each other. So, you can work with the <code>JXON</code> object by inserting the previous code at the beginning of your scripts. If you are not interested in a bidirectional conversion, don't use it, use only one of our algotithm instead.</p> + +<p>Sample usage:</p> + +<pre class="brush: js">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> + +<p>…the same thing using AJAX:</p> + +<pre class="brush: js">function reqListener () { + + var myObject = JXON.build(this.responseXML); + // we got our javascript object! + alert(JSON.stringify(myObject)); + + var newDoc = JXON.unbuild(myObject); + // we got our Document instance! + alert((new XMLSerializer()).serializeToString(newDoc)); + +}; + +var oReq = new XMLHttpRequest(); +oReq.onload = reqListener; +oReq.open("get", "example.xml", true); +oReq.send();</pre> + +<h4 id="JXON.build_syntax">JXON.build syntax</h4> + +<p><code>JXON.build(<a href="#JXON_build-document" title="JXON.build – @document"><em>document</em></a>[, <a href="#JXON_build-verbosity" title="JXON.build – @verbosity"><em>verbosity</em></a>[, <a href="#JXON_build-freeze" title="JXON.build – @freeze"><em>freeze</em></a>[, <a href="#JXON_build-nesteAttributes" title="JXON.build – @nesteAttributes"><em>nesteAttributes</em></a>]]])</code></p> + +<h4 id="JXON.build_description">JXON.build description</h4> + +<p>Returns a JavaScript <a href="/en/JavaScript/Reference/Global_Objects/Object" title="en/JavaScript/Reference/Global_Objects/Object"><code>Object</code></a> based on the given XML Document.</p> + +<h4 id="JXON.build_parameters">JXON.build parameters</h4> + +<dl> + <dt><code id="JXON_build-document">document</code></dt> + <dd>The XML document to be converted into JSON format.</dd> + <dt><code id="JXON_build-verbosity">verbosity</code> <span class="inlineIndicator optional optionalInline">Optional</span></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 href="#Algorithm_.234.3A_a_very_minimalist_way" title="Go to JXON algorithm #4">#4</a> to <a href="#Algorithm_.231.3A_a_verbose_way" title="Go to JXON algorithm #1">#1</a> (default value is <code>1</code>, which is equivalent to the <a href="#Algorithm_.233.3A_a_synthetic_technique" title="Go to JXON algorithm #3">algorithm #3</a>).</dd> + <dt><code id="JXON_build-freeze">freeze</code> <span class="inlineIndicator optional optionalInline">Optional</span></dt> + <dd>A boolean (optional) expressing whether the created object must be <a 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 id="JXON_build-nesteAttributes">nesteAttributes</code> <span class="inlineIndicator optional optionalInline">Optional</span></dt> + <dd>A boolean (optional) expressing whether the the <code>nodeAttributes</code> 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 id="JXON.unbuild_syntax">JXON.unbuild syntax</h4> + +<p><code>JXON.unbuild(<a href="#JXON_unbuild-objTree" title="JXON.unbuild – @objTree"><em>objTree</em></a>[, <a href="#JXON_unbuild-namespaceURI" title="JXON.unbuild – @namespaceURI"><em>namespaceURI</em></a>[, <a href="#JXON_unbuild-qualifiedNameStr" title="JXON.unbuild – @qualifiedNameStr"><em>qualifiedNameStr</em></a>[, <a href="#JXON_unbuild-documentType" title="JXON.unbuild – @objTree"><em>documentType</em></a>]]])</code></p> + +<h4 id="JXON.unbuild_description">JXON.unbuild description</h4> + +<p>Returns an XML Document based on the given JavaScript <a href="/en/JavaScript/Reference/Global_Objects/Object" title="en/JavaScript/Reference/Global_Objects/Object"><code>Object</code></a>.</p> + +<h4 id="JXON.unbuild_parameters">JXON.unbuild parameters</h4> + +<dl> + <dt><code id="JXON_unbuild-objTree">objTree</code></dt> + <dd>The JavaScript Object from which you want to create your XML Document.</dd> + <dt><code id="JXON_unbuild-namespaceURI">namespaceURI</code> <span class="inlineIndicator optional optionalInline">Optional</span></dt> + <dd>Is a <a href="https://developer.mozilla.org/en-US/docs/Web/API/DOMString" title="A UTF-16 String. As JavaScript already uses such strings, DOMString is mapped directly to a String."><code>DOMString</code></a> containing the namespace URI of the document to be created, or <code>null</code> if the document doesn't belong to one.</dd> + <dt><code id="JXON_unbuild-qualifiedNameStr">qualifiedNameStr</code> <span class="inlineIndicator optional optionalInline">Optional</span></dt> + <dd>Is a <a href="https://developer.mozilla.org/en-US/docs/Web/API/DOMString" title="A UTF-16 String. As JavaScript already uses such strings, DOMString is mapped directly to a String."><code>DOMString</code></a> containing the qualified name, that is an optional prefix and colon plus the local root element name, of the document to be created.</dd> + <dt><code id="JXON_unbuild-documentType">documentType</code> <span class="inlineIndicator optional optionalInline">Optional</span></dt> + <dd>Is the <a class="internal" href="https://developer.mozilla.org/En/DOM/DocumentType" title="En/DOM/DocumentType"><code>DocumentType</code></a> of the document to be created. It defaults to <code>null</code>.</dd> +</dl> + +<h3 id="nativeなElement.prototype_オブジェクトの拡張">nativeな<code><a href="/en-US/docs/Web/API/element" title="/en-US/docs/Web/API/element">Element</a>.prototype</code> オブジェクトの拡張</h3> + +<p>もしあなたが<code>.appendJXON()</code> メソッドを 全てのNativeな <a href="/en-US/docs/Web/API/element"><code>element</code></a> オブジェクトで使用したいなら, このコードのコメントをJXON libraryから外して下さい:</p> + +<pre class="brush: js"> /* Uncomment the following code if you want to enable the .appendJXON() method for *all* the "element" objects! */ + + /* + + Element.prototype.appendJXON = function (oObjTree) { + loadObjTree(document, this, oObjTree); + return this; + }; + + */</pre> + +<h4 id="例">例</h4> + +<p>Imagine you want to populate the following <a href="/en-US/docs/Web/API/HTMLElement"><code>HTMLElement</code></a> through JSON:</p> + +<pre class="brush: html"><div id="form_container"></div></pre> + +<p>Then, the following code:</p> + +<pre class="brush: js">document.getElementById("form_container").appendJXON({ + "form": { + "script": { + "@type": "text/javascript", + "keyValue": "\n function numbersOnly (oToCheckField, oKeyEvent) {\n return oKeyEvent.charCode === 0 || /\\d/.test(String.fromCharCode(oKeyEvent.charCode));\n }\n" + }, + "input": [{ + "@type": "hidden", + "@name": "instId", + "@value": 1234 + }, { + "@type": "hidden", + "@name": "currency", + "@value": "GBP" + }, { + "@type": "hidden", + "@name": "amount", + "@value": 0 + }, { + "@type": "hidden", + "@name": "name", + "@value": "CAPTURED" + }], + "table": { + "tr": [{ + "th": { + "@style": "text-align: right;", + "keyValue": "Product:" + }, + "td": { + "span": [{ + "input": { + "@type": "radio", + "@name": "nome", + "@id": "rel_tshirt", + "@value": "tshirt" + }, + "label": { + "@for": "rel_tshirt", + "keyValue": "T-Shirt" + }, + "@class": "product" + }, { + "input": { + "@type": "radio", + "@name": "nome", + "@id": "rel_trousers", + "@value": "trousers" + }, + "label": { + "@for": "rel_trousers", + "keyValue": "Trousers" + }, + "@class": "product" + }, { + "input": { + "@type": "radio", + "@name": "nome", + "@id": "rel_pullover", + "@value": "pullover" + }, + "label": { + "@for": "rel_pullover", + "keyValue": "Pullover" + }, + "@class": "product" + }] + } + }, { + "th": { + "@style": "text-align: right;", + "keyValue": "Quantity:" + }, + "td": { + "input": { + "@type": "text", + "@name": "myInput", + "@onkeypress": "return numbersOnly(this, event);", + "@onpaste": "return false;" + } + } + }] + }, + "p": { + "input": { + "@type": "submit", + "@value": "Purchase!" + } + }, + "@action": "https://secure-test.worldpay.com/wcc/purchase", + "@name": "BuyForm", + "@method": "POST" + } +});</pre> + +<p>will populate the previous element in the following way:</p> + +<pre class="brush: html"><div id="form_container"> + <form action="https://secure-test.worldpay.com/wcc/purchase" name="BuyForm" method="POST"> + <script type="text/javascript"> + function numbersOnly(oToCheckField, oKeyEvent) { + return oKeyEvent.charCode === 0 || /\d/.test(String.fromCharCode(oKeyEvent.charCode)); + } + </script> + <input type="hidden" name="instId" value="1234" /> + <input type="hidden" name="currency" value="GBP" /> + <input type="hidden" name="amount" value="0" /> + <input type="hidden" name="name" value="CAPTURED" /> + <table> + <tr> + <th style="text-align: right;">Product:</th> + <td><span class="product"><input type="radio" name="nome" id="rel_tshirt" value="tshirt"/><label for="rel_tshirt">T-Shirt</label></span><span class="product"><input type="radio" name="nome" id="rel_trousers" value="trousers"/><label for="rel_trousers">Trousers</label></span><span class="product"><input type="radio" name="nome" id="rel_pullover" value="pullover"/><label for="rel_pullover">Pullover</label></span> + </td> + </tr> + <tr> + <th style="text-align: right;">Quantity:</th> + <td> + <input type="text" name="myInput" onkeypress="return numbersOnly(this, event);" onpaste="return false;" /> + </td> + </tr> + </table> + <p> + <input type="submit" value="Purchase!" /> + </p> + </form> +</div></pre> + +<h3 id="ほかの例">ほかの例</h3> + +<h4 id="例_1_どのようにJXONがXMLドキュメントの代わりにHTMLドキュメントを生成するのか">例 #1: どのようにJXONがXMLドキュメントの代わりにHTMLドキュメントを生成するのか:</h4> + +<pre class="brush: js">/* The structure of my document */ +var oMyHTMLStruct = { + "html": { + "head": { + "meta": { + "@http-equiv": "Content-Type", + "@content": "text/html; charset=UTF-8" + }, + "title": "My HTML Document", + "script": { + "@type": "text/javascript", + "keyValue": "alert(\"Welcome!\");" + }, + "style": "p:first-letter {\n font: italic bold 30px Georgia, serif;\n}" + }, + "body": { + "h1": "My HTML Document", + "p": "Hello world!!" + } + } +}; + +/* Create the document */ +var oMyHTMLDoc = JXON.unbuild(oMyHTMLStruct, "http://www.w3.org/1999/xhtml");</pre> + +<p>…And here is the output of <code>alert((new XMLSerializer()).serializeToString(oMyHTMLDoc))</code>:</p> + +<pre class="brush: html"><html> + +<head> + <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> + <title>My HTML Document</title> + <script type="text/javascript"> + alert("Welcome!"); + </script> + <style> + p:first-letter { + font: italic bold 30px Georgia, serif; + } + </style> +</head> + +<body> + <h1>My HTML Document</h1> + <p>Hello world!!</p> +</body> + +</html></pre> + +<div class="note"><strong>Note:</strong> As we already said in <a href="#ordering-lossless-note">the note within <em>Code considerations</em></a>, despite the bidirectional conversion between XML and JSON <strong>is</strong> lossless regarding the whole content and the structure of an XML document, it <strong>is not</strong> lossless regarding the ordering of elements, which for some XML dialects (like XHTML) is part of the information. For instance, a bidirectional conversion of the following HTML paragraph: + +<pre class="brush: html"><p>She <strong>loves</strong> you. And definitely <strong>hates</strong> me.</p></pre> +would determine a result like the following: + +<pre class="brush: html"><p><strong>loves</strong><strong>hates</strong>Sheyou. And definitelyme.</p></pre> +As you can see in this special case, the whole information is preserved, the ordering of the elements is not.<br> +It turns out then that for some XML dialects JXON can be not the best choise, while it can be a really powerful tool in dealing with <em>standard XML</em>. One conversion method which is lossless for element order, as it relies on arrays (but, with a less human-readable, JavaScript-friendly syntax), is <a href="http://www.jsonml.org/" title="http://www.jsonml.org/">JsonML</a>.</div> + +<h3 id="このライブラリについて">このライブラリについて</h3> + +<p>The <code>JXON.build()</code> method summarizes all our four ways of conversion (see: <a href="#Algorithm_.231.3A_a_verbose_way" title="Go to JXON algorithm #1">#1</a>, <a href="#Algorithm_.232.3A_a_less_verbose_way" title="Go to JXON algorithm #2">#2</a>, <a href="#Algorithm_.233.3A_a_synthetic_technique" title="Go to JXON algorithm #3">#3</a>, <a href="#Algorithm_.234.3A_a_very_minimalist_way" title="Go to JXON algorithm #4">#4</a>). The result is therefore the same of our four algorithms, depending on the level of verbosity utilised. As above, optional properties and methods (commented in the example) of the <a href="#Algorithm_.231.3A_a_verbose_way" title="Go to JXON algorithm #1">first algorithm</a> (verbosity level: 3) are not included.</p> + +<p>The <code>JXON.unbuild()</code> method utilises our <a href="#Reverse_algorithms" title="Reverse algorithms">reverse algorithm</a>.</p> + +<p>Therefore, <strong>all <a href="#Code_considerations" title="Code considerations">code considerations</a> remain the same</strong>.</p> + +<h2 id="Resources">Resources</h2> + +<ul> + <li><a href="http://code.google.com/p/xml2json-xslt/wiki/TransformingRules" title="TransformingRules – xml2json-xslt">The Parker Convention</a></li> + <li><a href="http://badgerfish.ning.com/" title="BadgerFish convention">The BadgerFish Convention</a></li> + <li><a 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 href="http://www.w3.org/TR/microdata/#json">Converting HTML to other formats: JSON (The World Wide Web Consortium)</a></li> + <li><a 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 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> + <li><a href="http://davidwalsh.name/convert-xml-json" title="Convert XML to JSON with JavaScript – David Walsh Blog">Convert XML to JSON with JavaScript – David Walsh Blog</a></li> + <li><a href="http://goessner.net/download/prj/jsonxml/" title="http://goessner.net/download/prj/jsonxml/">http://goessner.net/download/prj/jsonxml/</a> – just another json2xml and xml2json conversion tool</li> + <li><a href="http://tawani.blogspot.it/2006/12/serialize-javascript-objects-to-xml-for.html" title="Serialize JavaScript objects to XML (for use with Ajax) – Tawani's Blog Rants">Serialize JavaScript objects to XML (for use with Ajax) – Tawani's Blog Rants</a></li> + <li><a href="http://www.kawa.net/works/js/xml/objtree-e.html" title="XML.ObjTree – XML source code from/to JavaScript object like E4X – Kawa.net">XML.ObjTree – XML source code from/to JavaScript object like E4X – Kawa.net</a></li> + <li><a href="http://www.jsonml.org/" title="http://www.jsonml.org/">JsonML</a> – a conversion method which is lossless for element order, as it relies on arrays.</li> +</ul> + +<h2 id="関連項目">関連項目</h2> + +<ul> + <li><a href="/en/XML" title="en/XML">XML</a></li> + <li><a href="/en/JSON" title="en/JSON">JSON</a></li> + <li><a href="/en/XPath" title="en/XPath">XPath</a></li> + <li><a href="/en/E4X" title="en/E4X">E4X (ECMAScript for XML)</a></li> + <li><a href="/en/Parsing_and_serializing_XML" title="en/Parsing_and_serializing_XML">Parsing and serializing XML</a></li> + <li><a href="/en/DOM/XMLHttpRequest" title="en/XMLHttpRequest">XMLHttpRequest</a></li> + <li><a href="/en/How_to_create_a_DOM_tree" title="en/How_to_create_a_DOM_tree">How to Create a DOM tree</a></li> + <li><a href="/en/JavaScript/Introduction_to_Object-Oriented_JavaScript" title="Introduction to Object-Oriented JavaScript">Introduction to Object-Oriented JavaScript</a></li> + <li><a href="/en/JavaScript/Guide/Working_with_Objects" title="Working with Objects">Working with Objects</a></li> + <li><a href="/en/XML_Introduction" title="en/XML_Introduction">XML Introduction</a></li> +</ul> |