0

我正在关注https://developer.mozilla.org/en-US/docs/JXON 编写一个将 xml 文件转换为 JSON 的算法。但是,没有运气。我觉得我做错了什么!

我应该在以下行中通过什么来代替“doc”:

 var myObject = new JXONTree(doc);  

我试过这个:

<!DOCTYPE html>  
<html lang="en">  
<head>  
<title>Welcome</title>  

<script type="text/javascript" src="sample1.js"></script>  

<script type="text/javascript">  

 /*  
 * Loading xml on the browser page  
 */  
function loadXML()  
{  
     try
    { 
         if (window.XMLHttpRequest)  
        {
             // code for IE7+, Firefox, Chrome, Opera, Safari  
             xmlhttp = new XMLHttpRequest();  
        }
        else  
        {  
            // code for IE6, IE5  
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");  
        }  
        xmlhttp.open("GET", "sample.xml", false);  
        xmlhttp.send();  
     }  
    catch(e)  
    {  
        alert("Please enable file access to read config file");  
    }  
    var response = xmlhttp.responseXML;  
    if (response == null)  
    {  
        alert("Error in xml file ..Please check config.xml file is valid or not !");  
    }  
    return response;  
 }  

function myFun()  
{  
    //Loading config xml  
    var xmlDoc = loadXML();  
    var myObject = new JXONTree(xmlDoc);  
     alert(myObject);  
} 
 </script>  

</head>  

 <body onload="myFun()">  
 Hello
</body>  
</html>  

我的 sample.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>

因此,在运行此程序时,我在 Opera 中收到如下错误:

请启用文件访问以读取配置文件。我在 Opera12 中启用了 Allow File XMLHttpRequest。还是没有运气!它适用于谷歌浏览器。那么我错过了什么?

请帮忙。

谢谢

4

2 回答 2

0

传递一个 DOMDocument对象。如果您使用 检索 XML 文档XMLHttpRequest,那么它将作为responseXML属性使用。否则,请使用以下内容:

var parser = new DOMParser();  // only available in some newer browsers
var doc = parser.parseFromString(yourXMLString, 'application/xml');
于 2013-03-21T04:52:19.077 回答
0

对我有用,@sneha,从答案开始icktoofay

我直接在 chrome canary 控制台中执行此操作:

输入:

navigator.userAgent

输出:

"Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1506.0 Safari/537.36"

输入:

prsr = new DOMParser()

输出:

DOMParser {parseFromString: function}

输入:

doc = '<?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>'

输入:

doc2 = prsr.parseFromString(doc, 'application/xml')

输出:

#document
<!DOCTYPE catalog SYSTEM "catalog.dtd">
<catalog>...</catalog>

输入:

/*\
|*|
|*|  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;
}

输入:

doc2.documentElement

输出:

<catalog>​…​&lt;/catalog>​

输入:

myObject = getJXONTree(doc2.documentElement);

输出:

myObject
Object {product: Object, script: Object}
product: Object
@description: "Cardigan Sweater"
catalog_item: Array[2]
__proto__: Object
script: Object
@type: "text/javascript"
keyValue: "function matchwo(a,b) {      if (a < b && a < 0) { return 1; }       else { return 0; }    }"
__proto__: Object
__proto__: Object
于 2013-05-14T20:59:49.997 回答