Writing XML in different character encodings using Java

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

The file script 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 records an XML document.

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

when I read in a file, I get an error message:

"not allowed in prolog"

this error does not occur if 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 to parse the UTF-16 file successfully.

code for parsing -

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

the last line returns an error.

+3
source share
1

LSSerializer writeToString .

setEncoding LSOutput, LSSerializer . LSOutput CharacterStream BufferedWriter, LSSerializer .

+2

Source: https://habr.com/ru/post/1747642/


All Articles