你可以将jaxb对象转换为org.w3c.dom.Element吗?

时间:2016-04-26 10:55:57

标签: java jaxb w3c

我从另一个不使用Java的部门获得了一些.xsd文件。我需要编写与指定格式相对应的xml。所以我jaxb将它们转换为Java类,我能够编写一些xml。到现在为止还挺好。但是现在其中一个元素/类包含一个属性,您可以(/您应该能够)插入任何xml。我需要在那里插入其他一个jaxb元素。

在java中,我们有:

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;
            }

        }

我要插入的对象属于这个类:

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

    @XmlElement(name = "ContactInfo", required = true)
    protected ContactInformationLetter contactInfo;
    ...

我希望我能做到这样的事情:

Letter letter = new Letter();

XMLDocument xmlDocument = new XMLDocument();
xmlDocument.setAny(letter);

但当然,字母不是“元素”类型。

1 个答案:

答案 0 :(得分:3)

您必须将其编组到一个文档中,您可以从中获取元素:

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());

参考:how to marshal a JAXB object to org.w3c.dom.Document?

相关问题