这给了我一个没有子节点的顶级节点的 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;
}
这是一种解决方法,它似乎效率更低,因为它先转换为 String,然后再转换为 Document。
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()));
}
是否有可能完成我想要完成的事情?