我有一个要求生成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>
我的问题是:
- 为什么
JAXB marshallers
不能嵌入 “CustomXMLAdapter
” 编组内容与家长一个(UserInfo.class)
。 - 我们有一个任何替代选项在
JAXB
做到这一点简单吗? - 如何指定
XMLAdapter
中的BoundType
,ValueType
。为了将内容嵌入到父类编组中,是否有任何特定类型?
+1对于提出的问题 – 2013-05-14 13:10:35