js xml 读取 方法

一:读本地xml

<script type="text/javascript">

var xml = new ActiveXObject("Microsoft.XMLDOM");

xml.async = false;

xml.load("../test5/xml/read1.xml");

var xsl = new ActiveXObject("Microsoft.XMLDOM");

xsl.async = false;

xsl.load("../test5/xml/read1.xml");

document.write(xml.transformNode(xsl));

</script>

二:子节点调用方法

XMl数据格式如下:

<?xml version="1.0" encoding="gb2312"?>

<root>

<item>

<name>刘亦菲</name>

<url>MingXing/LiuYiFei.htm</url>

<color>7A9D4B</color>

</item>

<item>

<name>蔡依林</name>

<url>MingXing/CaiYiLin.htm</url>

<color>FD0000</color>

</item>

<item>

<name>张娜拉</name>

<url>MingXing/ZhangNaLa.htm</url>

<color>7A9D4B</color>

</item>

<item>

<name>张韶涵</name>

<url>MingXiang/ZhangShaoHan.htm</url>

<color>0000FF</color>

</item>

<item>

<name>张靓颖</name>

<url>MingXing/ZhangLiangYin.htm</url>

<color>7A9D4B</color>

</item>

<item>

<name>李宇春</name>

<url>MingXing/LiYuChun.htm</url>

<color>7A9D4B</color>

</item>

<item>

<name>徐若瑄</name>

<url>MingXing/XuLuXuan.htm</url>

<color>FD0000</color>

</item>

</root>

var cdsales=new ActiveXObject("Microsoft.XMLDOM"); //创建XmlDom对象

cdsales.async=true; //使用异步加载

LoadSalesDoc()

cdsales.onreadystatechange=LoadedSales;

function LoadedSales()

{

    var txt="";

    if(cdsales.readyState==4)

    {

        if(cdsales.parseError.errorCode != 0) 

        {

            txt="";

        }else{

            var bi=cdsales.documentElement.selectNodes("item");

            if(bi!=null&&bi.length>0)

            {

                for(var i=0;i<bi.length;i++)

                {    

                    txt+="<li>·<a href="+bi[i].childNodes[1].text+" style=color:"+bi[i].childNodes[2].text+">"+bi[i].childNodes[0].text+"</a></li>";

                }

            }else{

                txt="";

            }

        }

    }else{

        txt="";

    }    

    sales.innerHTML=txt;

}

function LoadSalesDoc()

{

    var Url="/XML/Hot.xml";

    cdsales.load(Url);

}

三:节点属性读取方法

var cdsales=new ActiveXObject("Microsoft.XMLDOM"); //创建XmlDom对象

cdsales.async=true; //使用异步加载

var Url="../test5/xml/read2.xml";

cdsales.load(Url);

其它:

1.输出内容:document.write(txt)

   document.close() // close layout stream

2.输出内容到div

<script type="text/javascript">

    var sales=document.getElementById('sales');

    sales.innerHTML="txt";

</script>

<body>

<div id="sales"></div>

</body>

posted @ 2011-09-21 13:18  镇水古月  阅读(514)  评论(0编辑  收藏  举报