2013-05-14 57 views
2

我有一个要求生成XML文件下面使用JAXB2格式,它同时具有固定可变 XML内容。问题与JAXB XMLAdapter编组

什么是约束?

可变XML部分的含量应的一个的5个不同的XML schema(计划有JAXB2.0实现5个不同的Java类来生成它),这是需要被嵌入在固定XML内容。

XML格式:

<user_info> 
    <header>  //Fixed XML Part 
    <msg_id>..</msg_id> 
    <type>...</type> 
    </header> 
    <user_type> // Variable XML content 
         // (userType : admin, reviewer, auditer, enduser, reporter) 
    ........ 
    </user_type> 
</user_info> 

我试过吗?

我已为上述XML metadata创建了一个JAXB注释的Java类。对于可变的XML部分,我使用了共同的父类(BaseUserType),它被所有5个不同的类<user_type>扩展。并尝试使用@XmlJavaTypeAdapter覆盖marshall(..)操作。 (如下)

JAXB注解类:

@XmlRootElement(name="user_info") 
public class UserInfo { 

    private Header header; //reference to JAXB annotated Class Header.class 

    @XmlJavaTypeAdapter(value=CustomXMLAdapter.class) 
    private BaseUserType userType; // Base class - acts as a common Type 
            // for all 5 different UserType JAXB annotated Classes 

    // Getters setters here.. 
    // Also tried to declare JAXB annotations at Getter method 
} 

自定义XML适配器类别:

public class CustomXMLAdapter extends XmlAdapter<Writer, BaseInfo> { 
     private Marshaller marshaller=null; 

     @Override 
     public BaseInfo unmarshal(Writer v) throws Exception { 
      // Some Implementations here... 
     } 

     @Override 
     public Writer marshal(BaseInfo v) throws Exception { 
       OutputStream outStream = new ByteArrayOutputStream(); 
       Writer strResult = new OutputStreamWriter(outStream); 
       if(v instanceof CustomerProfileRequest){ 
        getMarshaller().marshal((CustomerProfileRequest)v, strResult); 
       } 
       return strResult; 
     } 

     private Marshaller getMarshaller() throws JAXBException{ 
       if(marshaller==null){ 
         JAXBContext jaxbContext = JAXBContext.newInstance(Admin.class, Reviewer.class, Enduser.class, Auditor.class, Reporter.class); 
         marshaller = jaxbContext.createMarshaller(); 
       } 
       return marshaller; 
     } 
} 

哪里我现在挣扎?

我没有面临任何错误或警告,正在生成XML(如下所示)。但产出不是预期的产出。它没有嵌入变量XML部分与正确的一个

输出

<user_info> 
     <header> 
      <msg_id>100</msg_id> 
      <type>Static</type> 
     </header> 
     <user_type/> // Empty Element, even though we binded the value properly. 
    </user_info> 

我的问题是:

  1. 为什么JAXB marshallers不能嵌入 “CustomXMLAdapter” 编组内容与家长一个(UserInfo.class)
  2. 我们有一个任何替代选项JAXB做到这一点简单吗?
  3. 如何指定XMLAdapter中的BoundType,ValueType。为了将内容嵌入到父类编组中,是否有任何特定类型?
+1

+1对于提出的问题 – 2013-05-14 13:10:35

回答

1

XmlAdapterXmlAdapter通过允许您从您的域对象转换为JAXB可以更好地处理用于编组/解组目的的另一个值对象。

如果从其他架构中的所有模型对象都是BaseUserType真子类,那么所有你需要做的是使JAXBContext意识到它们的存在。您可以在创建JAXBContext时通过冒号分隔包含所有包名称的字符串来执行此操作。

JAXBContext jc = JAXBContext.newInstance("com.example.common:com.example.foo:com.example.bar");