2

My situation: I have a method that accepts a byte array. The array in question is encoded using UTF-8 and was originally an XML message. I would like to be able to re-construct this message using a DOM parser. I know I can create a Document from a byte array through the use of a ByteBuffer. The only problem is that if I put this directly into action on the passed byte array, it will create a corrupted Document (if possible at all). That is because the array is an encoded XML message, encoded in UTF-8. However, when I decode the array by the use of the decode() method, I get a CharBuffer returned:

ByteBuffer encodedData = ByteBuffer.wrap(data);
CharBuffer decodedData = Charset.forName("UTF-8").decode(encodedData);

I don't know how to construct a Document from this, as there are no parse() methods defined in the DocumentBuilder that will accept a CharBuffer....

Could anyone help me with this?

1 Answer 1

5

DocumentBuilder has a parse(InputStream is) method, you can create your document by passing in a ByteArrayInputStream created from your bytes.

Document doc = DocumentBuilder.parse(new ByteArrayInputStream(data));
Sign up to request clarification or add additional context in comments.

1 Comment

Just as a note: This is one of the rare cases where you don't need to specify the encoding, because XML data has to contain enough information to find out the encoding itself (if it's well-formed).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.