JavaScript 解析XML

<html>
<body>
<script language="javascript" type="text/javascript">
   //xml字符串
   var xmlstring = '<?xml version=/"1.0/"?>/n'
   + '<shoppingcart date=/"14-10-2007/" total=/"123.45/">/n'
   + ' <item code=/"12345/">/n'
   + '   <name>Widget</name>/n'
   + '   <quantity>1</quantity>/n'
   + ' </item>/n'
   + ' <item code=/"54321/">/n'
   + '   <name>Another Widget</name>/n'
   +'   <quantity>2</quantity>/n'
   + ' </item>/n'
   + '</shoppingcart>';

   alert(xmlstring);


   try
   {
  
    // convert the string to an XML object
    // 用于 IE 的代码:
    if (window.ActiveXObject)
    {
     alert("activexobject");
     var xmlobject =new ActiveXObject("Microsoft.XMLDOM");
     xmlobject.async="false";
     xmlobject.loadXML(xmlstring);
    }

   // 用于 Mozilla, Firefox, Opera, 等浏览器的代码:
    else
    {
     alert("firefox");
     var parser=new DOMParser();
     var xmlobject =parser.parseFromString(xmlstring,"text/xml");
    }

   }
   catch (e)
   {
    alert('error');
  
   }

   // get the XML root item

   var root = xmlobject.getElementsByTagName('shoppingcart')[0];
   var date = root.getAttribute("date");

   alert("shoppingcart date=" + date);

   var items = root.getElementsByTagName("item");
   for (var i = 0 ; i < items.length ; i++) {

    // get one item after another
    var item = items[i];
    // now we have the item object, time to get the contents
    // get the name of the item
  
    var name = item.getElementsByTagName("name")[0].firstChild.nodeValue;
    // get the quantity
  
    var quantity = item.getElementsByTagName("quantity")[0].firstChild.nodeValue;
  
    alert("item #" + i + ": name=" + name + " quantity=" + quantity);
  
   }
</script>
</body>
</html>

 

 

 

你可能感兴趣的:(JavaScript 解析XML)