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();
}
谢谢安德烈亚斯的回答。你说得对,它很好用。我已经分析了文档的节点列表。他们都在那里。