如何将对象编组到元素

How to Marshall Object to Element

我正在尝试将一个对象混搭到 org.w3c.dom.Element,但它不起作用。 这是我的代码:

public static org.w3c.dom.Element writeXMLElement(Object nf) {
    JAXBContext context;
    try {
        context = JAXBContext.newInstance(Rodo.class);
        Marshaller marshaller = context.createMarshaller();
        org.w3c.dom.Element retorno = new org.w3c.dom.Element() {

            ...
        };
        marshaller.marshal(nf, retorno);
        return retorno;
    } catch (JAXBException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;
}

如果我写 XML 文件,它工作正常。但是对于 Element 我得到这个错误:

Exception in thread "main" java.lang.NullPointerException at com.sun.xml.internal.bind.marshaller.SAX2DOMEx.startElement(Unknown Source) at com.sun.xml.internal.bind.v2.runtime.output.SAXOutput.endStartTag(Unknown Source) at com.sun.xml.internal.bind.v2.runtime.XMLSerializer.endAttributes(Unknown Source) at com.sun.xml.internal.bind.v2.runtime.XMLSerializer.childAsSoleContent(Unknown Source) at com.sun.xml.internal.bind.v2.runtime.ClassBeanInfoImpl.serializeRoot(Unknown Source) at com.sun.xml.internal.bind.v2.runtime.XMLSerializer.childAsRoot(Unknown Source) at com.sun.xml.internal.bind.v2.runtime.MarshallerImpl.write(Unknown Source) at com.sun.xml.internal.bind.v2.runtime.MarshallerImpl.marshal(Unknown Source) at javax.xml.bind.helpers.AbstractMarshallerImpl.marshal(Unknown Source) at XMLWriter.writeXMLElement(XMLWriter.java:388) at HTMLCTeParse.getCTeBean(HTMLCTeParse.java:339) at GeraCTe.main(GeraCTe.java:12)

有谁知道怎么解决的吗? 谢谢! Br

我找到了其他解决方案:

How to marshall JAXBElement<Object> into org.w3c.dom.Element in Java using JAXB

You could marshal to a DOMResult:

DOMResult res = new DOMResult(); marshaller.marshal(myJaxbElement, res); Element elt = ((Document)res.getNode()).getDocumentElement();

还是谢谢你。 :)