XML文件转换成 HTML

前端之家收集整理的这篇文章主要介绍了XML文件转换成 HTML前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
packagecom.itheima.xml;

importjava.io.File;
importjava.io.FileInputStream;
importjava.io.PrintStream;

importjavax.xml.transform.Result;
importjavax.xml.transform.Source;
importjavax.xml.transform.Transformer;
importjavax.xml.transform.TransformerFactory;
importjavax.xml.transform.stream.StreamResult;
importjavax.xml.transform.stream.StreamSource;

publicclassTextXMLToHTML{
/**
*将XML转换成HTML
*@throwsException
*/
publicstaticvoidtranslate()throwsException{
//创建XML的文件输入流
FileInputStreamfis=newFileInputStream("F:/123.xml");
Sourcesource=newStreamSource(fis);

//创建XSL文件的输入流
FileInputStreamfis1=newFileInputStream("F:/123.xsl");
Sourcetemplate=newStreamSource(fis1);

PrintStreamstm=newPrintStream(newFile("F:/123.html"));
//讲转换后的结果输出到stm中即F:\123.html
Resultresult=newStreamResult(stm);
//根据XSL文件创建准个转换对象
Transformertransformer=TransformerFactory.newInstance().newTransformer(template);
//处理xml进行交换
transformer.transform(source,result);
//关闭文件流
fis1.close();
fis.close();
}

publicstaticvoidmain(String[]args){
try{
translate();
}catch(Exceptione){
System.out.println("XML转换成HTML失败:"+e.getMessage());
}
}
}

xml配置文件F:/123.xml

<?xmlversion="1.0"encoding="UTF-8"standalone="no"?>
<employees>
<employee-list>
<employee>
<id>001</id>
<name>李达</name>
<gender>男</gender>
<address>北京海淀</address>
</employee>
<employee>
<id>002</id>
<name>赵超</name>
<gender>男</gender>
<address>上海黄浦</address>
</employee>
<employee>
<id>003</id>
<name>张云</name>
<gender>女</gender>
<address>山东济南</address>
</employee>
</employee-list>
</employees>

xls配置文件F:/123.xsl

<?xmlversion="1.0"encoding="UTF-8"?>
<xsl:stylesheetversion="1.0"xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:outputmethod="html"encoding="UTF-8"doctype-public="-//W3C//DTDXHTML1.0Transitional//EN"doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"/>
<xsl:templatematch="/">

<htmlxmlns="http://www.w3.org/1999/xhtml">
<head>
<Metahttp-equiv="Content-Type"content="text/html;charset=UTF-8"/>
<title>员工信息</title>
</head>

<body>
<tablewidth="800px"border="1"bordercolor="#000000"style="border-collapse:collapse">
<tr>
<tdalign="center">编号</td>
<tdalign="center">姓名</td>
<tdalign="center">性别</td>
<tdalign="center">地址</td>
</tr>
<xsl:for-eachselect="employees/employee-list/employee">
<tr>
<tdalign="center"><xsl:value-ofselect="id"/></td>
<tdalign="center"><xsl:value-ofselect="name"/></td>
<tdalign="center"><xsl:value-ofselect="gender"/></td>
<tdalign="center"><xsl:value-ofselect="address"/></td>
</tr>
</xsl:for-each>

</table>
</body>
</html>

</xsl:template>
</xsl:stylesheet>

猜你在找的XML相关文章