JAXB generate xml with namespace for each element

﹥>﹥吖頭↗ 提交于 2019-12-11 04:02:06

问题


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>

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 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>

回答1:


For this use case I would do the following:

  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)).

For More Information

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


来源:https://stackoverflow.com/questions/9034515/jaxb-generate-xml-with-namespace-for-each-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!