JAXB为每个元素生成带有命名空间的xml [英] JAXB generate xml with namespace for each element

查看:711
本文介绍了JAXB为每个元素生成带有命名空间的xml的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用jaxb生成具有以下模式的xml。

How can i generate xml with following schema using jaxb.

<NS1:getRatesResponse xmlns:NS1="http://mynamespaceTypes">
<response>
    <NS2:rates xmlns:NS2="http://mynamespace">
        <currency>USD</currency>

    </NS2:rates>
    <NS3:rates xmlns:NS3="http://mynamespace">
        <currency>EUR</currency>

    </NS3:rates>
    <NS4:rates xmlns:NS4="http://mynamespace">
       ... etc
</response>


我不知道怎么告诉jaxb每个新项目应该是NS(n + 1)具有相同的命名空间。更改xml格式不是一个选项,因为它是外部的。

I dont know how to tell jaxb that every new item should be NS(n+1) with the same namespace. Changing xml format is not an option,because it`s external.

JAXB正确地解析了这个xml,但是当使用相同的类生成时它会像这样产生它:

JAXB parses this xml correctly, but when producing using same classes it produce it like this:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ns3:getRatesResponse
  xmlns:ns2="http://mynamespaceTypes" 
  xmlns:ns3="http://mynamespace">
 <response>
   <ns2:rates>
    <currency>EUR</currency>

   </ns2:rates>
   <ns2:rates>
    <currency>USD</currency>

   </ns2:rates>
 </response>
</ns3:getRatesResponse>


推荐答案

对于这个用例,我会做以下事情: / p>

For this use case I would do the following:


  1. 创建StAX XMLStreamWriter

  2. getRatesResponse 响应元素直接到 XMLStreamWriter

  3. marshaller.setProperty(Marshaller.JAXB_FRAGMENT,true); 上设置以下属性,以防止在每个编组调用上写入标头。

  4. Rate 对象中的每一个分别编组到 XMLStreamWriter

  5. 在Marshaller上设置一个 NamespacePrefixMapper 的实例来控制命名空间前缀(这当前需要JAXB RI,对此扩展的支持是目前正被添加到 EclipseLink JAXB(MOXy)中。

  1. Create a StAX XMLStreamWriter
  2. Write the getRatesResponse and response elements directly to the XMLStreamWriter
  3. Set the following property on marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true); to prevent the header from being written on each marshal call.
  4. Marshal each of the Rate objects to the XMLStreamWriter individually.
  5. On the Marshaller set an instance of NamespacePrefixMapper on it to control the namespace prefix (this currently requires the JAXB RI, support for this extension is currently being added to EclipseLink JAXB (MOXy)).

更多信息

  • http://blog.bdoughan.com/2011/11/jaxb-and-namespace-prefixes.html

这篇关于JAXB为每个元素生成带有命名空间的xml的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆