Java 从编组对象构造org.w3c.dom.Document

Java 从编组对象构造org.w3c.dom.Document,java,xml,dom,jaxb,Java,Xml,Dom,Jaxb,我想从我的封送对象构造一个org.w3c.dom.Document 我尝试过这篇文章中描述的内容,但没有成功 这是我的代码: public Document serialise() throws Exception { MyClass myObjectToMarshall = this.getObjectToMarshall(); JAXBContext jc = JAXBContext.newInstance(MyClass.class); Marshaller m =

我想从我的封送对象构造一个
org.w3c.dom.Document

我尝试过这篇文章中描述的内容,但没有成功

这是我的代码:

public Document serialise() throws Exception {
    MyClass myObjectToMarshall = this.getObjectToMarshall();
    JAXBContext jc = JAXBContext.newInstance(MyClass.class);
    Marshaller m = jc.createMarshaller();
    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    m.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
    m.marshal(myObjectToMarshall , System.out);
    StringWriter xml = new StringWriter();
    m.marshal(myObjectToMarshall , xml);
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    DocumentBuilder builder = factory.newDocumentBuilder();
    return builder.parse(new InputSource(new StringReader(xml.toString())));
}
当此指令
m.marshall(myObjectToMarshall,System.out)时执行后,我得到以下结果:

<myObjectToMarshall >
    <id>15</id>
    <code>MY_CODE</code>
    <label>MY_LABEL</label>
    <date>2015-09-15+02:00</date>
</myObjectToMarshall >
我想我的目标到马尔沙尔的编组是正确的

但是,当我使用IntelliJ,
builder.parse(new-InputSource(new-StringReader(xml.toString()))
调试最后一条指令时,我得到一个空文档:
[#Document:null]

还有其他属性需要设置吗

请你帮我弄清楚为什么文件是空的好吗

先谢谢你

另外,我正在使用java 7。

您的文档很好

实现了
toString()
方法以返回
“[“+getNodeName()+”:“+getNodeValue()+”]”
。文档的
nodeName
#document
,文档的
nodeValue
null
。请参阅的javadoc

如果需要DOM文档,请不要封送到
字符串中,然后解析文本。只需直接封送到DOM树中:

public Document serialise() throws Exception {
    MyClass myObjectToMarshall = this.getObjectToMarshall();
    JAXBContext jc = JAXBContext.newInstance(MyClass.class);
    DOMResult domResult = new DOMResult();
    jc.createMarshaller().marshal(myObjectToMarshall, domResult);
    return (Document)domResult.getNode();
}

谢谢安德烈亚斯的回答。你说得对,它很好用。我已经分析了文档的节点列表。他们都在那里。