Writing XML in different character encodings with Java

Posted by Roman Myers on Stack Overflow See other posts from Stack Overflow or by Roman Myers
Published on 2010-05-29T04:11:10Z Indexed on 2010/05/29 4:12 UTC
Read the original article Hit count: 349

Filed under:
|
|
|

I am attempting to write an XML library file that can be read again into my program.

The file writer code is as follows:

XMLBuilder builder = new XMLBuilder(); Document doc = builder.build(bookList); DOMImplementation impl = doc.getImplementation(); DOMImplementationLS implLS = (DOMImplementationLS) impl.getFeature("LS", "3.0"); LSSerializer ser = implLS.createLSSerializer(); String out = ser.writeToString(doc);

//System.out.println(out);

try{ FileWriter fstream = new FileWriter(location); BufferedWriter outwrite = new BufferedWriter(fstream); outwrite.write(out); outwrite.close(); }catch (Exception e){ }

The above code does write an xml document.

However, in the XML header, it is an attribute that the file is encoded in UTF-16.

when i read in the file, i get the error:

"content not allowed in prolog"

this error does not occur when the encoding attribute is manually changed to UTF-8.

I am trying to get the above code to write an XML document encoded in UTF-8, or successfully parse a UTF-16 file.

the code for parsing in is

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder loader = factory.newDocumentBuilder(); Document document = loader.parse(filename);

the last line returns the error.

© Stack Overflow or respective owner

Related posts about java

Related posts about Xml