原XML文件 目的是先按year分组,然后再在year中按照typeid分组
<?xml version="1.0" encoding="GB2312"?> 
<catalog> 
    <cd> 
        <title>Empire Burlesque </title> 
        <typeid>001 </typeid> 
        <year>1985 </year> 
    </cd> 
     <cd> 
        <title>Hide your heart </title> 
        <typeid>002 </typeid> 
        <year>1985 </year> 
    </cd> 
    <cd> 
        <title>Still got the blues </title> 
        <typeid>001 </typeid> 
        <year>1986 </year> 
    </cd> 
</catalog> 
要求转成如下格式: 
<?xml version="1.0" encoding="GB2312"?> 
<Result> 
    <Year id = "1985"> 
        <Typeid num = "001"> 
<title>Empire Burlesque </title> 
        </Typeid> 
        <Typeid num = "002"> 
<title>Hide your heart </title> 
        </Typeid> 
    </Year> 
    <Year id = "1986"> 
        <Typeid num = "001"> 
<title>Still got the blues </title> 
        </Typeid> 
    </Year> 
</Result>

解决方案 »

  1.   

    我觉得用XSLT比较麻烦,还是用dom4j好一点。
      

  2.   

    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                    xmlns:h="http://www.xml.org/pipe/HTTP"
                    >
        <xsl:output method="xml"/>    <xsl:template match="catalog">
            <root>
                 <xsl:for-each-group select="cd" group-by="year">
                     <year id="{current-grouping-key()}">
                         <xsl:for-each-group select="current-group()" group-by="typeid">
                             <typeid num="{current-grouping-key()}">
                                 <title><xsl:value-of select="current-group()/title"/></title>
                             </typeid>
                         </xsl:for-each-group>
                     </year>
                </xsl:for-each-group>
            </root>
        </xsl:template>   
    </xsl:stylesheet>
      

  3.   

    xsl:for-each-group是xslt2.0中的新特性,把楼上的写的样式表其中的版本号version改为2.0发现还是不行,下面是我是我操作xml和xslt的java代码:
             String src = "d:/xslt/test.xml";//原XML文件
            String dest= "d:/testResult.xml";要生成的XML文件
    String xslt="d:/xslt/test.xsl";//用来转化原XML文件的样式表
            File xmlFile = new File(src);
            File xsltFile = new File(xslt);
            File dest2 = new File(dest);
            Source xmlSource = new StreamSource(xmlFile);
            Source xsltSource = new StreamSource(xsltFile);
            StreamResult sr = new StreamResult (dest2.toString()); 
            TransformerFactory transFact =TransformerFactory.newInstance();
            Transformer trans = transFact.newTransformer(xsltSource);
            trans.transform(xmlSource, sr);
    执行完上述代码以后报如下错误:
    javax.xml.transform.TransformerException: Could not find function: current-grouping-key
    后来我采用在原XML文件中嵌入xslt样式表,然后用浏览器(IE6.0)打开XML文件报出以下提示:
    关键字 xsl:template 可能不包含 xsl:for-each-group。
    继续求解!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!