js通过xmldom调用xslt对xml排序输出的一个简单例子.

 

test.xml

<? xml version="1.0" encoding="utf-8"  ?>
<!--
<? xml-stylesheet type="text/xsl" href="Test.xsl" ?>-->
< root >
    
< item  id ="5"  name ="aa"   />
    
< item  id ="2"  name ="bb"   />
    
< item  id ="7"  name ="cc"   />
</ root >

 test.xsl

 

<? xml version="1.0" encoding="utf-8" ?>
< xsl:stylesheet  version ="1.0"  xmlns:xsl ="http://www.w3.org/1999/XSL/Transform" >
   
< xsl:template  match ="/" >
     
< table >
      
< xsl:for-each  select ="//item" >
    
< xsl:sort  order ="ascending"  select ="@id"  data-type ="number"   />
    
< tr >
    
< td >< xsl:value-of  select ="./@id"   /></ td >< td >< xsl:value-of  select ="./@name"   /></ td >
    
</ tr >
      
</ xsl:for-each >
     
</ table >
    
</ xsl:template >
</ xsl:stylesheet >

test.html

 

<! DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
< HTML >
< HEAD >
< TITLE > test </ TITLE >
< script  type ="text/javascript" >
    
function myFun(str)
    
{
            
var xmlDoc = new ActiveXObject("Msxml2.DOMDocument");
            xmlDoc.async 
= false;
            xmlDoc.load(
"test.xml");

            
var xslDoc = new ActiveXObject("Msxml2.DOMDocument");
            xslDoc.async 
= false;
            xslDoc.resolveExternals 
= false;
            xslDoc.load(
"test.xsl");

            
var sortNode = xslDoc.selectSingleNode("//xsl:sort");
            
//alert(sortNode.attributes[1].value);
            //alert(sortNode);
            sortNode.attributes[1].value = "@" + str;
            document.getElementById(
"divContainer").innerHTML = xmlDoc.transformNode(xslDoc);
            
//alert("OK");
    }

</ script >
</ HEAD >

< BODY >
< input  value ="try sort by id"  type ="button"  onclick ="myFun('id')"   />  
< input  value ="try sort by name"  type ="button"  onclick ="myFun('name')"   />
< div  id ="divContainer"   />
</ BODY >
</ HTML >

当然,不一定是xml,xsl要存为文件,也可以是符合规范的字串. 用loadxml方法加载即可.

要支持ff,那么换一种声明方法.

 

你可能感兴趣的:(xml,button,XSL,encoding,XSLT,stylesheet)