javascript - How can I traverse XML in an HTML document? -


i need save data offline, save data xml. don't know how xml object javascript.

 <xml id=xmldata>         <data>             <tb1>                <id>1</id>                <name>1</name>             </tb1>             <tb1>                <id>2</id>                <name>2</name>             </tb1>         </data>     </xml>     <html id="mainform">     <head id="head1">      </head>     <body>     <script type="text/javascript">     var xmldoc;     // code ie     if (window.activexobject)     {     xmldoc=new activexobject("microsoft.xmldom");     }     // code mozilla, firefox, opera, etc.     else if (document.implementation.createdocument)     {     xmldoc=document.implementation.createdocument("","",null);     }     else     {     alert('your browser cannot handle script');     }     xmldoc.async=false;     xmldoc.load("");//how can xml?      var x=xmldoc.documentelement.childnodes;      (var i=0;i<x.length;i++)     {      if (x[i].nodetype==1)       {        //process element (nodetype 1) nodes       document.write(x[i].nodename + ": ");       document.write(x[i].childnodes[0].nodevalue);       document.write("<br />");       }      }     </script>     </body>     </html> 

try this:

var txt='<xml id=xmldata><data><tb1><id>1</id> <name>1</name></tb1><tb1><id>2</id><name>2</name></tb1></data></xml>';  if (window.domparser) {     parser=new domparser();     xmldoc=parser.parsefromstring(txt,"text/xml"); } else // internet explorer {    xmldoc=new activexobject("microsoft.xmldom");    xmldoc.async=false;    xmldoc.loadxml(txt); }  var x=xmldoc.documentelement.childnodes;  (var i=0;i<x.length;i++) {      if (x[i].nodetype==1)     {         //process element (nodetype 1) nodes        console.log(x[i].nodename + ": ");        console.log(x[i].childnodes[0].nodevalue);        console.log("<br />");     }  } 

fiddle: http://jsfiddle.net/hb5e9/


Comments