如何将 JAXB 对象封送到 org.w3c.dom.Document?
2022-09-02 20:20:21
这给了我一个 Document 对象,其中包含一个没有子节点的顶级节点:
public static Document getDocument(Object jaxb)
{
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
//dbf.setNamespaceAware(true);
Document doc = dbf.newDocumentBuilder().newDocument();
JAXBContext context = JAXBContext.newInstance(jaxb.getClass());
context.createMarshaller().marshal(jaxb, doc);
return doc;
}
这是解决方法,似乎效率更高,因为它转换为字符串,然后转换为文档。
public static Document getDocument(Object jaxb)
{
StringWriter writer = new StringWriter();
JAXBContext context = JAXBContext.newInstance(jaxb.getClass());
context.createMarshaller().marshal(jaxb, writer);
return DocumentBuilderFactory.newInstance().newDocumentBuilder().
parse(new InputSource(new StringReader(writer.toString()));
}
是否有可能完成我想要完成的任务?