如何将数组字节转换为org.w3c.dom.Document

时间:2014-01-16 15:25:34

标签: java xml bytearray

我有一个Document(org.w3c.dom.Document),我将此文档转换为byte数组:

private byte[] obtenerBytesDeDocument(Document documentoXml) throws Exception {
    Source source = new DOMSource( documentoXml );
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    Result result = new StreamResult(out);
    TransformerFactory factory = TransformerFactory.newInstance();
    Transformer transformer = factory.newTransformer();
    transformer.transform(source, result);
    byte[] butesXml =  out.toByteArray();
    return butesXml;
}

我需要将byte数组转换为document:

private Document obtenerDocumentDeByte(byte[] documentoXml) throws Exception {
        ...
}

有什么想法吗?

Thansks !!!

1 个答案:

答案 0 :(得分:15)

以下情况应该有效。

private Document obtenerDocumentDeByte(byte[] documentoXml) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    DocumentBuilder builder = factory.newDocumentBuilder();
    return builder.parse(new ByteArrayInputStream(documentoXml));
}