Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I'm trying to save a tree (extends JTree) which holds an XML document to a DOM Object having changed it's structure.

I have created a new document object, traversed the tree to retrieve the contents successfully (including the original encoding of the XML document), and now have a ByteArrayInputStream which has the tree contents (XML document) with the correct encoding.

The problem is when I parse the ByteArrayInputStream the encoding is changed to UTF-8 (in the XML document) automatically.

Is there a way to prevent this and use the correct encoding as provided in the ByteArrayInputStream.

It's also worth adding that I have already used the
transformer.setOutputProperty(OutputKeys.ENCODING, encoding); method to retrieve the right encoding.

Any help would really be appreciated.

share|improve this question
Can your share a bit of your code? – gawi Aug 26 '10 at 18:59

2 Answers

I solved it, given alot of trial and errors.

I was using OutputFormat format = new OutputFormat(document);
but changed it to OutputFormat format = new OutputFormat(d, encoding, true);
and this solved my problem.

encoding is what I set it to be
true refers to whether or not indent is set.

Note to self - read more carefully - I had looked at the javadoc hours ago - if only I'd have read more carefully.

share|improve this answer
// Read XML
String xml = "xml"
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(new InputSource(new StringReader(xml)));

// Append formatting
OutputFormat format = new OutputFormat(document);

if (document.getXmlEncoding() != null) {
  format.setEncoding(document.getXmlEncoding());
}

format.setLineWidth(100);
format.setIndenting(true);
format.setIndent(5);
Writer out = new StringWriter();
XMLSerializer serializer = new XMLSerializer(out, format);
serializer.serialize(document);
String result = out.toString();
share|improve this answer
4  
Some explanation of this code would be useful for those who come and read this answer later. – Andrew Barber Dec 17 '12 at 14:59

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.