Visualizzazione dei risultati da 1 a 2 su 2
  1. #1
    Utente di HTML.it L'avatar di carlomarx
    Registrato dal
    Oct 2009
    Messaggi
    1,669

    Conversione di un documento XML in un oggetto javascript

    Ciao a tutt*.
    Ho creato questo script che spero sia utile a chiunque abbia la necessità di convertire un documento XML in un oggetto JavaScript. Sono partito da uno script già fatto, ma l'ho migliorato parecchio... I due documenti qui postati vanno ovviamente creati nella stessa cartella!

    documento da leggere (example.xml):
    codice:
    <ALEXA VER="0.9" URL="davidwalsh.name/" HOME="0" AID="=">
      <SD TITLE="A" FLAGS="" HOST="davidwalsh.name">
        <TITLE TEXT="David Walsh Blog :: PHP, MySQL, CSS, Javascript, MooTools, and Everything Else"/>
        <LINKSIN NUM="1102"/>Hello
        <SPEED TEXT="1421" PCT="51"/>World!
        <FAVOURITE />
      </SD>
      <SD>
        <POPULARITY URL="davidwalsh.name/" TEXT="7131"/>
        <REACH RANK="5952"/>
        <RANK DELTA="-1648"/>
      </SD>
    </ALEXA>
    pagina HTML da cui avviene la lettura:
    codice:
    <html>
    <head>
    <title>XML to JavaScript Object conversion example</title>
    <script type="text/javascript">
    // a normal XMLHttpRequest function: it retrieves a file via XMLHTTPRequest, then calls fncCallback when done.
    function XHR(sURL, fncCallback /*, argumentToPass1, argumentToPass2, etc. */) {
    	var oResp, aArgs = Array.prototype.slice.call(arguments, 2);
    	if (window.XMLHttpRequest) { oResp = new XMLHttpRequest(); }
    	else if (window.ActiveXObject) { oResp = new ActiveXObject("Microsoft.XMLHTTP"); }
    	if (oResp) {
    		if (fncCallback) {
    			if (typeof oResp.onload !== "undefined")
    				oResp.onload = function() {
    					fncCallback.apply(oResp, aArgs);
    					oResp = null;
    				};
    			else {
    				oResp.onreadystatechange = function() {
    					if (oResp.readyState === 4) {
    						fncCallback.apply(oResp, aArgs);
    						oResp = null;
    					}
    				};
    			}
    		}
    		oResp.open("GET", sURL, true);
      		oResp.setRequestHeader("Content-Type", "text/plain");
    		oResp.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
    		oResp.send(null);
    	}
    }
    
    // recursive function which converts an XML DOM to a JavaScript Object
    function xml2Obj (oXMLDom) {
    	var oRObj = true;
    	if (oXMLDom.nodeType === 3) { // text
    		oRObj = oXMLDom.nodeValue.replace(/^\s+|\s+$/g, "");
    	} else {
    		if (oXMLDom.nodeType === 1) { // element
    			// do attributes
    			if (oXMLDom.attributes.length > 0) {
    				var iAttrib;
    				oRObj = {};
    				oRObj["@attributes"] = {};
    				for (var iAttrId = 0; iAttrId < oXMLDom.attributes.length; iAttrId++) {
    					iAttrib = oXMLDom.attributes.item(iAttrId);
    					oRObj["@attributes"][iAttrib.nodeName] = iAttrib.nodeValue;
    				}
    			}
    		}
    		// do children
    		if (oXMLDom.hasChildNodes()) {
    			var iKey, iValue, iXMLNode;
    			if (oRObj === true) { oRObj = {}; }
    			for (var iChildId = 0; iChildId < oXMLDom.childNodes.length; iChildId++) {
    				iXMLNode = oXMLDom.childNodes.item(iChildId);
    				iKey = iXMLNode.nodeType === 3 ? "@content" : iXMLNode.nodeName;
    				iValue = xml2Obj(iXMLNode);
    				if (oRObj.hasOwnProperty(iKey)) {
    					if (iXMLNode.nodeType === 3) { oRObj[iKey] += iValue; }
    					else {
    						if (oRObj[iKey].constructor !== Array) { oRObj[iKey] = [oRObj[iKey]]; }
    						oRObj[iKey].push(iValue);
    					}
    				} else if (iXMLNode.nodeType !== 3 || iValue !== "") { oRObj[iKey] = iValue; }
    			}
    	 	}
    	}
    	return(oRObj);
    };
    
    // function called via ajax callback
    function myFunction() {
    	// gets the object
    	var oMyObject = xml2Obj(this.responseXML);
    
    	// converts the object to a string and displays it in an alert message
    	alert(JSON.stringify(oMyObject));
    }
    </script>
    </head>
    
    <body>
    
    
    <span onclick="XHR('example.xml', myFunction);" style="cursor: pointer;">Click me!</span></p>
    </body>
    </html>
    carlomarx

  2. #2
    Utente di HTML.it L'avatar di carlomarx
    Registrato dal
    Oct 2009
    Messaggi
    1,669
    Scusate i troppi post, ma ho perfezionato ulteriormente lo script... meglio questa seconda versione, valida per tutti i formati XML.

    documento XML da leggere (example.xml):
    codice:
    <?xml version="1.0"?>
    <?xml-stylesheet href="catalog.xsl" type="text/xsl"?>
    <!DOCTYPE catalog SYSTEM "catalog.dtd">
    <catalog>
       <product description="Cardigan Sweater" product_image="cardigan.jpg">
          <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>
             <price>42.50</price>
             <size description="Small">
                <color_swatch image="red_cardigan.jpg">Red</color_swatch>
                <color_swatch image="navy_cardigan.jpg">Navy</color_swatch>
                <color_swatch image="burgundy_cardigan.jpg">Burgundy</color_swatch>
             </size>
             <size description="Medium">
                <color_swatch image="red_cardigan.jpg">Red</color_swatch>
                <color_swatch image="navy_cardigan.jpg">Navy</color_swatch>
                <color_swatch image="burgundy_cardigan.jpg">Burgundy</color_swatch>
                <color_swatch image="black_cardigan.jpg">Black</color_swatch>
             </size>
             <size description="Large">
                <color_swatch image="navy_cardigan.jpg">Navy</color_swatch>
                <color_swatch image="black_cardigan.jpg">Black</color_swatch>
             </size>
             <size description="Extra Large">
                <color_swatch image="burgundy_cardigan.jpg">Burgundy</color_swatch>
                <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>
    pagina HTML da cui avviene la lettura:
    codice:
    <!doctype html>
    <html>
    <head>
    <meta content="text/html; charset=UTF-8" http-equiv="Content-Type" />
    <title>XML to JavaScript Object conversion example</title>
    <script type="text/javascript">
    /**
    * a normal XMLHttpRequest function: it retrieves a file via XMLHTTPRequest, then calls the "callbackFnc" function when done.
    **/
    function XHR(sURL, callbackFnc /*, argumentToPass1, argumentToPass2, etc. */) {
    	var oResp, aArgs = Array.prototype.slice.call(arguments, 2);
    	if (window.XMLHttpRequest) { oResp = new XMLHttpRequest(); }
    	else if (window.ActiveXObject) { oResp = new ActiveXObject("Microsoft.XMLHTTP"); }
    	if (oResp) {
    		if (callbackFnc) {
    			if (typeof oResp.onload !== "undefined")
    				oResp.onload = function() {
    					callbackFnc.apply(oResp, aArgs);
    					oResp = null;
    				};
    			else {
    				oResp.onreadystatechange = function() {
    					if (oResp.readyState === 4) {
    						callbackFnc.apply(oResp, aArgs);
    						oResp = null;
    					}
    				};
    			}
    		}
    		oResp.open("GET", sURL, true);
      		oResp.setRequestHeader("Content-Type", "text/plain");
    		oResp.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
    		oResp.send(null);
    	}
    }
    
    /**
    * the recursive function which converts an XML Document to a JavaScript Object;
    * it will consider only the following node types and their attributes:
    * - Document,
    * - Element,
    * - Text,
    * - CDATASection;
    * all other informations will be lost!
    * it is a conscious choice.
    * please, see: http://www.w3schools.com/dom/dom_nodetype.asp
    **/
    function xml2Obj (oXMLNode) {
    	// default value for empty elements; it could be replaced with "null" instead of "true"... but i prefer so, because the truth is what appears :-)
    	var vResult = true;
    	// node attributes
    	if (oXMLNode.attributes && oXMLNode.attributes.length > 0) {
    		var iAttrib;
    		vResult = {};
    		vResult["@attributes"] = {};
    		for (var iAttrId = 0; iAttrId < oXMLNode.attributes.length; iAttrId++) {
    			iAttrib = oXMLNode.attributes.item(iAttrId);
    			vResult["@attributes"][iAttrib.nodeName] = iAttrib.nodeValue;
    		}
    	}
    	// children
    	if (oXMLNode.hasChildNodes()) {
    		var iKey, iValue, iXMLChild;
    		if (vResult === true) { vResult = {}; } // if above you have changed the default value, then it must be also replaced within this "if statement" in the same way...
    		for (var iChild = 0; iChild < oXMLNode.childNodes.length; iChild++) {
    			iXMLChild = oXMLNode.childNodes.item(iChild);
    			if ((iXMLChild.nodeType & 7) === 1) { // nodeType is "Document" (9) or "Element" (1)
    				iKey = iXMLChild.nodeName;
    				iValue = xml2Obj(iXMLChild);
    				if (vResult.hasOwnProperty(iKey)) {
    					if (vResult[iKey].constructor !== Array) { vResult[iKey] = [vResult[iKey]]; }
    					vResult[iKey].push(iValue);
    				} else { vResult[iKey] = iValue; }
    			} else if ((iXMLChild.nodeType - 1 | 1) === 3) { // nodeType is "Text" (3) or "CDATASection" (4)
    				iKey = "@content";
    				iValue = iXMLChild.nodeType === 3 ? iXMLChild.nodeValue.replace(/^\s+|\s+$/g, "") : iXMLChild.nodeValue;
    				if (vResult.hasOwnProperty(iKey)) { vResult[iKey] += iValue; }
    				else if (iXMLChild.nodeType === 4 || iValue !== "") { vResult[iKey] = iValue; }
    			}
    		}
    	}
    	return(vResult);
    }
    
    // function called via ajax callback
    function myFunction() {
    	// converts the XML document got via XMLHttpRequest
    	var oMyObject = xml2Obj(this.responseXML);
    
    	// converts the resultant object to a string and displays it in a textarea
    	document.outputForm.outputBox.value = JSON.stringify(oMyObject);
    }
    </script>
    </head>
    
    <body>
    <h1>&amp;ldquo;XML Document&amp;rdquo; to &amp;ldquo;JavaScript Object&amp;rdquo; conversion example</h1>
    <form name="outputForm">
    
    
    <textarea name="outputBox" style="width: 100%; height: 300px;"></textarea></p>
    <p style="text-align: center"><input type="button" name="convertBtn" onclick="XHR('example.xml', myFunction);" value="Click me!" style="font-size: 24px;" /></p>
    
    
    &amp;hellip;I'll try to load the &amp;ldquo;example.xml&amp;rdquo; file.</p>
    </form>
    </body>
    </html>
    carlomarx

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2025 vBulletin Solutions, Inc. All rights reserved.