【发布时间】:2015-12-12 00:38:26
【问题描述】:
我想从我的编组对象构造一个org.w3c.dom.Document。
我已经尝试了topic 中描述的内容,但没有成功。
这是我的代码:
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.marshal(myObjectToMarshall , System.out);被执行时,我得到以下结果:
<myObjectToMarshall >
<id>15</id>
<code>MY_CODE</code>
<label>MY_LABEL</label>
<date>2015-09-15+02:00</date>
</myObjectToMarshall >
我猜 myObjectToMarshall 的编组已正确完成。
但是,当我使用 IntelliJ 调试最后一条指令时,builder.parse(new InputSource(new StringReader(xml.toString()))),我得到一个空文档:[#document: null]
还有其他要设置的属性吗?
请您帮我理解为什么文档为空?
提前谢谢你。
附:我正在使用 java 7。
【问题讨论】: