为每个元素生成带有名称空间的XML [英] Generate XML with namespace for each element

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

问题描述

如何使用JAXB使用以下模式生成XML.

How can I generate XML with the 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>
</NS1:getRatesResponse>

我不知道如何告诉JAXB每个新项目都应该是具有相同名称空间的NS(n + 1).不能选择更改XML格式,因为它是外部的.

I don't 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 produces 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>

推荐答案

对于此用例,我将执行以下操作:

For this use case I would do the following:

  1. 创建StAX XMLStreamWriter
  2. getRatesResponse response 元素直接写入 XMLStreamWriter
  3. marshaller.setProperty(Marshaller.JAXB_FRAGMENT,true); 上设置以下属性,以防止在每次元帅调用时写入标头.
  4. 分别将每个 Rate 对象编组到 XMLStreamWriter .
  5. 在Marshaller上为其设置 NamespacePrefixMapper 的实例以控制名称空间前缀(当前需要JAXB RI,对此扩展的支持目前已添加到
  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)).

更多信息

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

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