当前位置: 代码迷 >> J2EE >> 怎么用xsl转xml文件,java代码如何写
  详细解决方案

怎么用xsl转xml文件,java代码如何写

热度:22   发布时间:2016-04-22 00:48:48.0
如何用xsl转xml文件,java代码怎么写
现在有一个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代码应该怎么写?


------解决方案--------------------
Java code
    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();        }    }
  相关解决方案