Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can you convert a jaxb object to org.w3c.dom.Element?

Tags:

java

jaxb

w3c

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".

like image 848
Albert Hendriks Avatar asked Apr 26 '16 10:04

Albert Hendriks


1 Answers

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?

like image 161
beat Avatar answered Oct 11 '22 23:10

beat