【问题标题】:How to marshall JAXB object to a different schema?如何将 JAXB 对象编组到不同的模式?
【发布时间】:2013-02-12 22:18:31
【问题描述】:

我解组具有特定格式的 XML,例如

<root>
   <a/>
   <b/>
   <c>
     <x/>
   </c>
   <d/>
</root>

在使用 Java 对象后,我想将它发送到另一个使用不同架构的服务,例如

<anotherRoot>
   <a/>
   <x/>
   <something>
      <d/>
   </something>
</anotherRoot>

这可以通过 JAXB “轻松”完成吗?

【问题讨论】:

  • 认为更多细节将有助于回答。,
  • 你试过什么?您是否尝试过在指定不同模式的同时编组对象?似乎快速尝试可能会回答您的问题...另外,也许您可​​以编写一种将一个 java 对象转换为另一个的方法。
  • 这是一个如何使用 EclipseLink JAXB (MOXy) 完成的示例:blog.bdoughan.com/2011/09/…

标签: java xml jaxb


【解决方案1】:

使用任何JAXB (JSR-222) 实现,您可以在JAXBSourcejavax.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);

完整示例

【讨论】:

    【解决方案2】:

    您可以为其他服务创建代理,并将其 bean 视为简单的数据传输对象。

    因此,当您希望调用服务时,您可以根据适当模型对象(您使用的模型对象,包含业务逻辑的对象)的值手动填充 bean 并使用 bean 调用服务。

    如果服务接口发生变化,您可以重新创建代理,编译器将帮助您修复转换。

    【讨论】:

      猜你喜欢
      • 2013-06-09
      • 1970-01-01
      • 2012-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-13
      • 2016-10-27
      • 2011-04-10
      相关资源
      最近更新 更多