How to convert XML to HTML using XSLT in Java

匿名 (未验证) 提交于 2019-12-03 01:57:01

问题:

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

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.

XML file

                   1             John             25           20000                      2             Tony             27             23000                       3             Eithen             29             25000      

XSL file

      

Java Code

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();     } } }

回答1:

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.

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.



回答2:

Your code works fine. In the question stylesheet node was not closed.

     

Also check the xsl path properly or test by

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


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!