你可以将一个jaxb对象转换为org.w3c.dom.Element吗?
问题描述:
我从另一个不使用Java的部门获得了一些.xsd文件。我需要编写对应于指定格式的xml。所以我jaxb-将它们转换为Java类,并且我能够编写一些xml。到现在为止还挺好。但是现在,其中一个元素/类包含一个属性,您可以(/您应该能够)插入任何xml。我需要在其中插入一个其他jaxb元素。你可以将一个jaxb对象转换为org.w3c.dom.Element吗?
在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);
但当然信不是“元素”类型。
答
您必须编组到一个文件,从中可以得到元素(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());