2017-09-05 51 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