2016-04-26 87 views
1

我從另一個不使用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); 

但當然信不是「元素」類型。

回答

2

您必須編組到一個文件,從中可以得到元素(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()); 

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

相關問題