Can I create a DOM Document from an encoded UTF-8 byte array?
My situation:
I have a method that accepts 开发者_JAVA百科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?
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));
精彩评论