2011-06-09 76 views
3

我正在使用XSL将我的XML文件配置为较小的XML。我的代码片段是这样:文件过早结束错误

public class MessageTransformer { 

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

     Transformer transformer = transformerFactory.newTransformer (new StreamSource("sample.xsl")); 
     transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); 
     transformer.setOutputProperty(OutputKeys.INDENT, "yes"); 
     transformer.setOutputProperty(OutputKeys.METHOD, "xml"); 
     transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); 
     transformer.transform(new StreamSource ("sample.xml"), 
      new StreamResult(new FileOutputStream("sample.xml")) 
     ); 
    } 
    catch (Exception e) { 
     e.printStackTrace(); 
    }  
} 
} 

当我使用XSL文件来转换XML手动我不有任何问题,我得到这个错误

ERROR: 'Premature end of file.' 
ERROR: 'com.sun.org.apache.xml.internal.utils.WrappedRuntimeException: Premature end of file.' 

。但是,这个JAVA文件无法转换。

会出现什么问题?

+0

我觉得让StreamSource(你原来的xml)和StreamResult(xslt后的结果)指向同一个文件,可能会让你陷入困境。 – Wivani 2011-06-09 10:53:58

回答

6

您正从同一个文件进行流式传输。尝试将其更改为这样的事情:

transformer.transform(new StreamSource ("sample.xml"), 
     new StreamResult(new FileOutputStream("sample_result.xml")) 
    ); 
+0

我刚刚通过使用不同的方法解决。但你的报价也是如此。可能会对其他人有用。谢谢;) – gencay 2011-06-09 10:55:43

+9

@gencay - 你能告诉我们你是如何解决它的? – Ben 2012-03-25 01:04:08

0

完成XML文件给任何标签其他明智的,它会给一个错误:文件过早结束。

<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?> 
<Customer> 
<person> 
    <Customer_ID>1</Customer_ID> 
    <name>Nirav Modi</name> 
</person> 
<person> 
    <Customer_ID>2</Customer_ID> 
    <name>Nihar dave</name> 
</person> 
</Customer> 

像这样,然后再试一次。

相关问题