毕业论文开发语言企业开发JAVA技术.NET技术WEB开发Linux/Unix数据库技术Windows平台移动平台嵌入式论文范文英语论文
您现在的位置: 毕业论文 >> java技术 >> 正文

java如何用xsl转xml文件

更新时间:2012-8-22:  来源:毕业论文

现在有一个cdcatalog.xml文件,
<?xml version="1.0" encoding="ISO-8859-1"?>
<catalog>
  <cd>
  <title>Empire Burlesque</title>
  <artist>Bob Dylan</artist>
  <country>USA</country>
  <company>Columbia</company>
  <price>10.90</price>
  <year>1985</year>
  </cd>
  <cd>
  <title>Fmpire Burlesque</title>
  <artist>FBob Dylan</artist>
  <country>FUSA</country>
  <company>FColumbia</company>
  <price>20.90</price>
  <year>2005</year>
  </cd>
</catalog>
和一个cdcatalog.xsl文件,内容如下:
<?xml version="1.0" encoding="ISO-8859-1"?>

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/">
  <html>
  <body>
  <h2>My CD Collection</h2>
  <table border="1">
  <tr bgcolor="#9acd32">
  <th align="left">Title</th>
  <th align="left">Artist</th>
  </tr>
  <xsl:for-each select="catalog/cd">
  <tr>
  <td><xsl:value-of select="title"/></td>
  <td><xsl:value-of select="artist"/></td>
  </tr>
  </xsl:for-each>
  </table>
  </body>
  </html>
</xsl:template>

</xsl:stylesheet>

想把转换后的结果输出到result.xml文件中,
请问java代码应该怎么写?
 public static void main(String[] args) {
        String xmlFileName = "d:/cdcatalog.xml";
        String xslFileName = "d:/cdcatalog.xsl";
        String htmlFileName = "d:/out.xml";
        transform(xmlFileName, xslFileName, htmlFileName);
    }

    public static void transform(String xmlFileName, String xslFileName,
            String htmlFileName) {
        try {
            TransformerFactory tFac = TransformerFactory.newInstance();
            Source xslSource = new StreamSource(xslFileName);
            Transformer t = tFac.newTransformer(xslSource);
            File xmlFile = new File(xmlFileName);
            File htmlFile = new File(htmlFileName);
            Source source = new StreamSource(xmlFile);
            Result result = new StreamResult(htmlFile);           
            t.transform(source, result);
        } catch (TransformerConfigurationException e) {
            e.printStackTrace();
        } catch (TransformerException e) {
            e.printStackTrace();
        }
    }

设为首页 | 联系站长 | 友情链接 | 网站地图 |

copyright©youerw.com 优尔论文网 严禁转载
如果本毕业论文网损害了您的利益或者侵犯了您的权利,请及时联系,我们一定会及时改正。