如何在 Java 中使用 XSLT 将 XML 转换为 HTML

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19811581/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 20:23:09  来源:igfitidea点击:

How to convert XML to HTML using XSLT in Java

javaxmlxsltxslt-1.0

提问by user2960161

I want to convert XML file into HTML file with help of XSLT. But I am getting an error i.e.

我想在 XSLT 的帮助下将 XML 文件转换为 HTML 文件。但我收到一个错误,即

javax.xml.transform.TransformerException: javax.xml.transform.TransformerException: com.sun.org.apache.xml.internal.utils.WrappedRuntimeException: Invalid byte 1 of 1-byte UTF-8 sequence.

javax.xml.transform.TransformerException: javax.xml.transform.TransformerException: com.sun.org.apache.xml.internal.utils.WrappedRuntimeException: 1 字节 UTF-8 序列的字节 1 无效。

XML file

XML文件

<?xml version="1.0"?>
<Company>
    <Info>
            <EmpId>1</EmpId>
            <EmpName>John</EmpName>
            <Age>25</Age>
          <Salary>20000</Salary>
   </Info>
    <Info>
            <EmpId>2</EmpId>
            <EmpName>Tony</EmpName>
            <Age>27</Age>
            <Salary>23000</Salary>
    </Info>
    <Info>
            <EmpId>3</EmpId>
            <EmpName>Eithen</EmpName>
            <Age>29</Age>
            <Salary>25000</Salary>
    </Info>
</Company>

XSL file

XSL文件

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
   <xsl:template match="/">
      <html>
         <body>
            <h1>Company Details</h1>
            <table border="1">
               <tr>
                  <th>EmpId</th>
                  <th>EmpName</th>
                  <th>Age</th>
                  <th>Salary</th>
               </tr>
               <xsl:for-each select="Company/Info">
                  <tr>
                     <td>
                        <xsl:value-of select="EmpId" />
                     </td>
                     <td>
                        <xsl:value-of select="EmpName" />
                     </td>
                     <td>
                        <xsl:value-of select="Age" />
                     </td>
                     <td>
                        <xsl:value-of select="Salary" />
                     </td>
                  </tr>
               </xsl:for-each>
            </table>
         </body>
      </html>
   </xsl:template>
</xsl:stylesheet>

Java Code

Java代码

public class TransInfoHtml 
{
public static void main(String args[])
{
try {
        TransformerFactory tFactory=TransformerFactory.newInstance();

        Source xslDoc=new StreamSource("files/NewStylesheet.xsl");
        Source xmlDoc=new StreamSource("D:/Demo.xml");

        String outputFileName="CompanyInfo.html";

        OutputStream htmlFile=new FileOutputStream(outputFileName);
        Transformer trasform=tFactory.newTransformer(xslDoc);
        trasform.transform(xmlDoc, new StreamResult(htmlFile));
    } 
    catch (FileNotFoundException e) 
    {
        e.printStackTrace();
    }
    catch (TransformerConfigurationException e) 
    {
        e.printStackTrace();
    }
    catch (TransformerFactoryConfigurationError e) 
    {
        e.printStackTrace();
    }
    catch (TransformerException e) 
    {
        e.printStackTrace();
    }
}
}

回答by vels4j

Your code works fine. In the question stylesheetnode was not closed.

你的代码工作正常。在问题stylesheet节点没有关闭。

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

Also check the xsl path properly or test by

还要正确检查 xsl 路径或通过以下方式测试

Source xslDoc=new StreamSource("D:/NewStylesheet.xsl");`

回答by Mathias Müller

To me, this looks like an encoding problem. Try to ensure that the files are encoded correctly in all cases.

对我来说,这看起来像是一个编码问题。尽量确保文件在所有情况下都正确编码。

For example, add encoding="UTF-8"to your XML and XSLT file. But note that this is only a declaration - it does not change the characters themselves.

例如,添加encoding="UTF-8"到您的 XML 和 XSLT 文件。但请注意,这只是一个声明——它不会改变字符本身。

Also, you could copy your XML content into a simple editor and save it explicitly as UTF-8. For instance, if you are using windows, copy the content into notepad, hit "Save as...". In the file dialog, you can choose "UTF-8" from a drop-down.

此外,您可以将 XML 内容复制到一个简单的编辑器中,并将其显式保存为 UTF-8。例如,如果您使用的是 Windows,请将内容复制到记事本中,点击“另存为...”。在文件对话框中,您可以从下拉列表中选择“UTF-8”。

回答by SHoko

For the special case of convert XHTML pages to HTML, we can use the HTMLWriterfrom the dom4jAPI.

对于转换XHTML页面为HTML的特殊情况下,我们可以使用HTMLWriterDOM4JAPI。

@Test
public void givenXHTML_whenWrite_thenGetHTML() throws Exception {
    String xml = "<?xml version='1.0' encoding='UTF-8' ?>" +
      "<html> <body><![CDATA[First&nbsp;test]]> " +
      "<img alt=\"W3C\" height=\"48\" width=\"72\" src=\"http://www.w3.org/Icons/w3c_home\" />" +
      "</body> </html>";
    Document document = DocumentHelper.parseText(xml);
    StringWriter buffer = new StringWriter();
    HTMLWriter writer = new HTMLWriter(buffer);
    String expects = "\n<html>\n" +
      "  <body>First&nbsp;test\n    "
      + "<img alt=\"W3C\" height=\"48\" width=\"72\" src=\"http://www.w3.org/Icons/w3c_home\">\n  "
      + "</body>\n" + "</html>\n";

    writer.write(document);
    String output = buffer.toString();

    assertThat(output).isEqualTo(expects);
}