2017-09-05 84 views
1

我有如下配置的xml表示。JAXB和實例化類的動態選擇

<definitions> 
    <definition type="MessageReception"> ... </definition> 
    <definition type="MessageProcessing"> ... </definition> 
    <definition type="ResponseGeneration"> ... </definition> 
</definition> 

如您所見,定義類型取決於屬性「type」。 我想用JAXB框架解開這個問題。但我只找到非常基本的情況下的JAXB使用的例子,比如像標題,作者,年份等平面屬性的書...

有沒有簡單的方法來做我想做的事情?

回答

0

當您爲「定義」創建內部類時,您應該用註釋@XmlAttribute標記「類型」成員。

這裏是給定xml的基本工作演示;

public class UnmarshalJaxbDemo { 


    public static void main(String[] args) { 
     StringBuffer xmlStr = new StringBuffer("<definitions>"+ 
            "<definition type=\"MessageReception\"> ... </definition>"+ 
            "<definition type=\"MessageProcessing\"> ... </definition>"+ 
            "<definition type=\"ResponseGeneration\"> ... </definition>"+ 
            "</definitions>"); 
     try { 
      JAXBContext context = JAXBContext.newInstance(Definitions.class); 
      Unmarshaller jaxbUnmarshaller = context.createUnmarshaller(); 
      Definitions definitions = (Definitions) jaxbUnmarshaller.unmarshal(new StreamSource(new StringReader(xmlStr.toString()))); 

      for (Definition defitinion : definitions.getDefinition()) { 
       System.out.println(defitinion.getType()); 
      } 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 

    @XmlAccessorType(XmlAccessType.FIELD) 
    public static class Definition { 

     @XmlAttribute 
     private String type; 

     public String getType() { 
      return type; 
     } 

     public void setType(String type) { 
      this.type = type; 
     } 

    } 

    @XmlRootElement(name = "definitions") 
    @XmlAccessorType(XmlAccessType.FIELD) 
    public static class Definitions { 
     private List<Definition> definition; 

     public List<Definition> getDefinition() { 
      return definition; 
     } 

     public void setDefinition(List<Definition> definition) { 
      this.definition = definition; 
     } 

    } 

} 
+0

您好,非常感謝您的回答。我意識到我的問題不夠具體,所以我會編輯它:我想根據「類型」屬性來實例化不同的定義的子類型,這是我的難題。 – Joel

0

您可以使用xsi:type來指示jaxb對類進行實例化。 例如:

<definitions> 
    <definition xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="messageReception"> 
     <receptionField>foo</receptionField> 
    </definition> 
    <definition xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="messageProcessing"> 
     <processingField>bar</processingField> 
    </definition> 
    <definition xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="responseGeneration"> 
     <generationField>baz</generationField> 
    </definition> 
</definitions> 

package your.package 

class MessageReception { 
    // getters and setters omitted 
    String receptionField; 
} 

jaxbContext = JAXBContext.newInstance("your.package"); 
Unmarshaller unmarshaller = mJaxbContext.createUnmarshaller(); 
DefinitionList definitionList = (DefinitionList) unmarshaller.unmarshal(inputStream); 
+0

謝謝我要去試試! – Joel