您的位置:首页 > Web前端 > JavaScript

js解析XML

2015-10-27 18:23 495 查看
xml文件

book.xml

<?xml version="1.0" encoding="utf-8" ?>
<bookstore >
  <book genre="novel" publicationdate="1967" ISBN="0-201-63361-2">
    <title>The Confidence Man</title>
    <author> Melville. Herman</author>
    <price>11.99</price>
  </book>
  <book genre="philosophy" publicationdate="1991" ISBN="1-861001-57-6">
    <title>The Gorgias</title>
    <author> Plato. Sidas</author>
    <price>9.99</price>
  </book>
</bookstore>


js解析(例子仅适用于IE浏览器)

// JavaScript Document
 var xmlDocument=new ActiveXObject("Msxml2.DOMDocument");
  xmlDocument.async = "false" ;//<span style="font-family: Arial, Helvetica, sans-serif;">关闭</span><span style="font-family: Arial, Helvetica, sans-serif;">异步加载</span>
  xmlDocument.load("book.xml");//加载xml文件
 function jeixiXML(){
 var childs=xmlDocument.documentElement.childNodes////获取根节点下的所有子节点
	 for(var j=0;j<childs.length;j++){
	    var attr=xmlDocument.documentElement.childNodes[j].attributes;//获取子节点的属性
	 	alert(attr[0].nodeName+"="+attr[0].nodeValue+"----"+attr[1].nodeName+"="+attr[1].value+"----"+attr[2].nodeName+"="+attr[2].value);
	  var node_addr=xmlDocument.selectNodes("//book");//获取book节点的所有子节点
	 for(var i=0;i<=xmlDocument.documentElement.childNodes.length;i++){
	  var title=node_addr[j].childNodes(i).text;	 
	      alert(title);	 
		 }
		 
 }
	}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: