简体   繁体   中英

How can I convert object (JAXB) or byte[] (from this object) to `org.w3c.dom.Element`?

I have Java class (JAXB) for example:

Test test = new Test();
test.set....
//fill test object
............

Now I need convert this object to org.w3c.dom.Element

Now I have converter for converte to byte[] :

public <T> byte[] marshal(T value) {
    try {
      StringWriter sw = new StringWriter();
      Marshaller marshaller = jaxbContext.createMarshaller();
      marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
      marshaller.marshal(value,sw);
      return sw.toString().getBytes();
    } catch (JAXBException e) {
      throw new RuntimeException(e.getMessage());
    }
  }

And My question: How can I convert test or byte[] to to org.w3c.dom.Element ?

EDIT:

answer the question in the commentary why I need it

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAnyElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import org.w3c.dom.Element;

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "any"
})
@XmlRootElement(name = "MessagePrimaryContent")
public class MessagePrimaryContent {

    @XmlAnyElement
    protected Element any;


    public Element getAny() {
        return any;
    }


    public void setAny(Element value) {
        this.any = value;
    }

}

I need set My object to setAny method. Such protocol and format. I did not invent it

First of all, instead of @XmlAnyElement Element any I'd use @XmlAnyElement(lax = true) Object any . Then you can simply assign your test to any and let JAXB marshal it. See this answer:

https://stackoverflow.com/a/9692275/303810

Thus you could avoid pre-marshalling as DOM.


Now, to your question.

You basically want to marshal your test object as a DOM element. The easiest would be to marshal to a DOMResult and then get the element from there.

Something like:

  marshaller = jaxbContext.createMarshaller();
  DOMResult domResult = new DOMResult();
  marshaller.marshal(value, domResult);
  Node rootNode = domResult.getNode();
  // I'm not quite sure that it's always a Document, but it's easy to figure out
  final Element rootElement = ((Document) rootNode).getDocumentElement();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM