以文本方式查看主题

-  W3CHINA.ORG讨论区 - 语义网·描述逻辑·本体·RDF·OWL  (http://bbs.xml.org.cn/index.asp)
--  『 XSL/XSLT/XSL-FO/CSS 』  (http://bbs.xml.org.cn/list.asp?boardid=8)
----  [原创]小妹初涉XSLT,求实现如下XML模型转换的样式表,希望能帮忙调一下,感激不尽  (http://bbs.xml.org.cn/dispbbs.asp?boardid=8&rootid=&id=79466)


--  作者:math0423
--  发布时间:1/12/2010 10:56:00 AM

--  [原创]小妹初涉XSLT,求实现如下XML模型转换的样式表,希望能帮忙调一下,感激不尽
这是根据实际问题抽象出来的模型如下:
原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>

下面是我写的样式表:
<?xml version="1.0" encoding="GB2312"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="2.0" encoding="GB2312" indent="yes" cdata-section-elements="DataContent "  />
<xsl:template match="/">
<Result>
<xsl:for-each-group select="catalog/cd" group-by="year">
<Year>
  <xsl:attribute name="id">
    <xsl:value-of select="year" />
  </xsl:attribute>
<xsl:for-each-group select="catalog/cd" group-by="typeid">
        <Typeid >
   <xsl:attribute name="num">
    <xsl:value-of select="typeid" />
  </xsl:attribute>
<title>><xsl:value-of select="title"/></title>
        </Typeid>
</xsl:for-each-group>
</Year>
</xsl:for-each-group>
</Result>  
</xsl:template>
</xsl:stylesheet>
下面是我写的java+XSKT转换xml用的java代码,有熟悉的提点意见或者有没有更好的java方法,请不吝指教。
        String src = "d:/xslt/test.xml";
        String dest= "d:/testResult.xml";
        String xslt="d:/xslt/test.xsl";
        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.setOutputProperty("encoding", "gb2312");
        trans.transform(xmlSource, sr);

有熟悉的麻烦帮写一下能用的xslt样式表给参考下,感激涕零!


W 3 C h i n a ( since 2003 ) 旗 下 站 点
苏ICP备05006046号《全国人大常委会关于维护互联网安全的决定》《计算机信息网络国际联网安全保护管理办法》
31.250ms