我有一個要求生成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