views:

40

answers:

1

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.

+1  A: 

the LSSerializer writeToString method does not allow the Serializer to pick a encoding.

with the setEncoding method of an instance of LSOutput, LSSerializer's write method can be used to change encoding. the LSOutput CharacterStream can be set to an instance of the BufferedWriter, such that calls from LSSerializer to write will write to the file.

Roman Myers