Search code examples
xmlstax

StreamWriting XML in any encoding


I've been trying to write XML as output using javax.xml.stream.XMLOutputFactory.createXMLStreamWriter(). Getting stuck on the XML Declaration when not using UTF-8.

   String encoding = "ISO-8859-1";    
   File testFile = new File(xmlOutFile);    
   OutputStream ops = new FileOutputStream(testFile);    
   xmlWriter = factory.createXMLStreamWriter(ops,encoding);    

  ...    
  String version = "1.0";    
  String encoding = "ISO-8859-1";    
  xmlWriter.writeStartDocument(encoding, version); 

XML input file being re-written;

<?xml version="1.0" encoding="ISO-8859-1"?>    
<definition attr1="toady"></definition> 

No error is thrown, the file is created, but it's empty. If I set the xmlWriter to UTF-8, the file is written.


Solution

  • The only problem here turned out to be lack of a file close statement: xmlWriter.close(). It wasn't obvious because in my real code, the process starts with an END_DOCUMENT in the first parser that must make it to the END_DOCUMENT handler that generates the XML. I was thrown off by the fact that UTF-8 worked anyway.