我希望在 Java 中创建 XML 文档对象并将它们序列化为字节数组(在通过 TCP 连接发送它们之前)。我目前的代码如下所示:
public byte [] EncapsulateThingy( ThingyType thingy )
{
parser.reset(); // parser is a pre-existing DocumentBuilder object
Document doc = parser.newDocument();
doc.appendChild( doc.createElement("Thingy") );
// ... add nodes to doc to represent thingy
ByteArrayOutputStream outputStream = new ByteArrayOutputStream( 8192 );
//
// Missing: Write doc to outputStream with xml version 1.0 and UTF-8
// encoding.
//
return outputStream.toByteArray();
}
The Sun Java documentation有关于一组接口(interface)的信息,这些接口(interface)似乎以 DomImplementationLS 开头,用于加载和保存 XML,我可以用它来轻松地填充上面缺失的部分。但我不知道如何创建一个实现 DomImplementationLS 的对象。
我的最终目标是将非常简单的对象序列化和反序列化为字节数组中编码的 XML,以便我可以通过网络传输它们。我有兴趣保持解决方案的轻量级,以便它可以处理高吞吐量的消息。
我对替代解决方案感兴趣,只要它们让我指定发送的确切 XML 结构即可。
我当然必须在使用这些 XML 消息时提供反序列化,但是在线有大量文档和教程可用于读取 XML,但用于编写 XML 的文档和教程却很少。
我更喜欢 Java 6 中包含的解决方案而不添加包。
最佳答案
希望这有帮助:
import java.io.ByteArrayOutputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.junit.Test;
import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.ls.DOMImplementationLS;
import org.w3c.dom.ls.LSOutput;
import org.w3c.dom.ls.LSSerializer;
public class DomLsTest {
@Test
public void testDomLs() throws Exception {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
DOMImplementation di = db.getDOMImplementation();
Document d = di.createDocument("", "foo", null);
Element e = d.createElement("bar");
d.getDocumentElement().appendChild(e);
DOMImplementationLS ls = (DOMImplementationLS) di;
LSOutput lso = ls.createLSOutput();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
lso.setByteStream(baos);
LSSerializer lss = ls.createLSSerializer();
lss.write(d, lso);
System.out.println(baos.toString());
}
}
因此,对于您的代码,您需要执行以下操作:
DOMImplementationLS ls = (DOMImplementationLS) parser.getDOMImplementation();
LSOutput lso = ls.createLSOutput();
lso.setByteStream(...);
LSSerializer lss = ls.createSerializer();
lss.write(..., lso);
关于Java Dom实现LS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/620250/