【问题标题】:Construct org.w3c.dom.Document from marshalled object从编组对象构造 org.w3c.dom.Document
【发布时间】: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。

【问题讨论】:

    标签: java xml dom jaxb


    【解决方案1】:

    你的文档很好。

    toString() 方法实现返回"["+getNodeName()+": "+getNodeValue()+"]"。文档的nodeName#document,文档的nodeValuenull。参见Node的javadoc。

    如果您想要一个 DOM 文档,请不要编组为 String 然后解析文本。直接编组到 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();
    }
    

    【讨论】:

    • 谢谢安德烈亚斯的回答。是的,它工作得很好。我已经解析了 Document 的节点列表。他们都在那里。
    猜你喜欢
    • 2013-06-09
    • 2012-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-13
    • 2022-08-19
    • 1970-01-01
    • 2014-11-19
    相关资源
    最近更新 更多