I got some .xsd files from another department that doesn't use Java. I need to write xml that corresponds to the specified format. So I jaxb-converted them to Java classes and I'm able to write some of the xml. So far so good. But now one of the element/classes contains a property where you can (/you're supposed to be able to) insert any xml. I need to insert one of the other jaxb elements there.
In java, we have:
import org.w3c.dom.Element;
...
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"any"
})
public static class XMLDocument {
@XmlAnyElement
protected Element any;
/**
* Gets the value of the any property.
*
* @return
* possible object is
* {@link Element }
*
*/
public Element getAny() {
return any;
}
/**
* Sets the value of the any property.
*
* @param value
* allowed object is
* {@link Element }
*
*/
public void setAny(Element value) {
this.any = value;
}
}
And the object I want to insert, is of this class:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"contactInfo",
...
})
@XmlRootElement(name = "Letter")
public class Letter {
@XmlElement(name = "ContactInfo", required = true)
protected ContactInformationLetter contactInfo;
...
I was hoping I could do something like this:
Letter letter = new Letter();
XMLDocument xmlDocument = new XMLDocument();
xmlDocument.setAny(letter);
But of course letter is not of type "Element".
You must marshall it to a Document, from which you can get the Element(s):
Letter letter = new Letter();
// convert to DOM document
Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
JAXBContext context = JAXBContext.newInstance(Letter.class.getPackage().getName());
Marshaller marshaller = context.createMarshaller();
XMLDocument xmlDocument = new XMLDocument();
xmlDocument.setAny(document.getDocumentElement());
Reference: how to marshal a JAXB object to org.w3c.dom.Document?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With