[英]How to marshall JAXB object to a different schema?
我解組了一種特定格式的XML,例如
<root>
<a/>
<b/>
<c>
<x/>
</c>
<d/>
</root>
在使用Java對象之后,我想將它發送到另一個使用不同模式的服務,例如
<anotherRoot>
<a/>
<x/>
<something>
<d/>
</something>
</anotherRoot>
這可以通過JAXB“輕松”完成嗎?
使用任何JAXB(JSR-222)實現,您可以在JAXBSource
和javax.xml.transform
API上使用XSLT來生成輔助XML結構:
JAXBContext jc = JAXBContext.newInstance(Foo.class);
// Output XML conforming to first XML Schema
Marshaller marshaller = jc.createMarshaller();
marshaller.marshal(foo, System.out);
// Create Transformer on Style Sheet that converts XML to
// conform the second XML Schema
TransformerFactory tf = TransformerFactory.newInstance();
StreamSource xslt = new StreamSource(
"src/example/stylesheet.xsl");
Transformer transformer = tf.newTransformer(xslt);
// Source
JAXBSource source = new JAXBSource(jc, foo);
// Result
StreamResult result = new StreamResult(System.out);
// Transform
transformer.transform(source, result);
完整的例子
您可以為其他服務創建創建代理,並將其bean視為簡單的數據傳輸對象。
因此,當您希望調用該服務時,您可以根據正確的模型對象(您使用的那個,包含業務邏輯的對象)的值手動填充bean,並使用bean調用該服務。
如果服務接口發生更改,您可以重新創建代理,編譯器將幫助您修復轉換。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.