Home > Web Front-end > HTML Tutorial > XML DOM traverse Xml document_html/css_WEB-ITnose

XML DOM traverse Xml document_html/css_WEB-ITnose

WBOY
Release: 2016-06-24 12:00:02
Original
984 people have browsed it

1.xml document content:

<?xml version="1.0" encoding="utf-8" ?><bookstore>  <book category="children">    <title lang="en">Harry Potter</title>    <author>J K. Rowling</author>    <year>2005</year>    <price>29.99</price>  </book>  <book category="cooking">    <title lang="en">Everyday Italian</title>    <author>Giada De Laurentiis</author>    <year>2005</year>    <price>30.00</price>  </book>  <book category="web">    <title lang="en">Learning XML</title>    <author>Erik T. Ray</author>    <year>2003</year>    <price>39.95</price>  </book>  <book category="web">    <title lang="en">XQuery Kick Start</title>    <author>James McGovern</author>    <author>Per Bothner</author>    <author>Kurt Cagle</author>    <author>James Linn</author>    <author>Vaidyanathan Nagarajan</author>    <year>2003</year>    <price>49.99</price>  </book></bookstore>
Copy after login

2. Encapsulate the parsing xml document function into the loadxmldoc.js file

function loadXMLDoc(dname) {try //Internet Explorer  {  xmlDoc=new ActiveXObject("Microsoft.XMLDOM");//创建空的微软xml文档对象  }catch(e)  {  try //Firefox, Mozilla, Opera, etc.    {    xmlDoc=document.implementation.createDocument("","",null);//其他浏览器通过解析器创建xml文档对象    }  catch(e) {alert(e.message)}  }try   {  xmlDoc.async=false;//关闭异步加载,确保文档加载完之前解析器不会继续执行脚本  xmlDoc.load(dname);//加载文档  return(xmlDoc);//返回xml文档对象  }catch(e) {alert(e.message)}return(null);}
Copy after login

3. Traverse all nodes under the xml document

<script type="text/javascript" src="Scripts/loadxmldoc.js">//引入loadxmldoc.js文件</script><script type="text/javascript">    xmlDoc = loadXMLDoc("books.xml");//创建文档对象    x = xmlDoc.documentElement.childNodes;//获取根节点下的子节点    for (i = 0; i < x.length; i++) {        if (1==x[i].nodeType){//是否为元素节点            document.write(x[i].nodeName);//标签名            document.write("<br/>");            y = x[i].childNodes;//获取子节点            for (j = 0; j < y.length; j++) {                if (1==y[j].nodeType) {//是元素节点                    document.write(y[j].nodeName);//标签名                    document.write(":");                    document.write(y[j].childNodes[0].nodeValue);//文本                    document.write("<br/>");                }            }            document.write("<br/>");        }    }</script>
Copy after login

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template