Problem with Java XML charset

  • Thread starter Erik A. Brandstadmoen
  • Start date
E

Erik A. Brandstadmoen

I'm having problems building a DOM document with java using a ny other
character set than utf-8.

The code snippet at the further down produces the following output. Why?
I explicitly produce an XML document using iso8859-1 charset, so why
does Java suddenly think I want utf-8 instead?

Is there any way to tell the DocumentBuilder classes that I want to work
with a character set different from utf-8? I haven't been able to figure
out.

Thanks in advance.

Erik B.

$ java TestXMLEncoding
Result: <?xml version="1.0" encoding="utf-8"?><definisjonsark/>
$


Hvorfor og hvor og hva er det som forandrer tegnsettet?

Erik.


Code :

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.StringWriter;

import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.xml.sax.SAXException;

/*
* Created on Dec 23, 2004
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/

/**
* @author mfreab
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public class TestXMLEncoding {

public static void main(String[] args)
throws IOException,
SAXException,
ParserConfigurationException {

TestXMLEncoding test = new TestXMLEncoding();

test.testXML();

}

public TestXMLEncoding() {

}

public void testXML() throws IOException, SAXException,
ParserConfigurationException {

Document xmlDocument = null;


DocumentBuilderFactory factory =
DocumentBuilderFactory.newInstance();
//factory.setValidating(true);
factory.setNamespaceAware(true);

final DocumentBuilder builder = factory.newDocumentBuilder();




System.out.println("Result: " + this.getAsString(xmlDocument));

}


private String getAsString(Document doc) {

String retVal = null;

try {
// Prepare the DOM docuemnt for writing
Source source = new DOMSource(doc);

// Prepare the result string
StringWriter w = new StringWriter();
Result result = new StreamResult(w);

// Write the DOM document to file
Transformer xformer =
TransformerFactory.newInstance().newTransformer();
xformer.transform(source,result);

retVal = w.getBuffer().toString();

} catch (TransformerConfigurationException tce) {
tce.printStackTrace();
} catch (TransformerException te) {
te.printStackTrace();
}

return retVal;
}


}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,969
Messages
2,570,161
Members
46,709
Latest member
AustinMudi

Latest Threads

Top