Reputation: 7084
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
Upvotes: 0
Views: 1900
Reputation: 43651
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:
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();
Upvotes: 1