JAXB绑定嵌套元素 [英] JAXB binding nested elements

查看:69
本文介绍了JAXB绑定嵌套元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用JAXB-impl.我需要能够将嵌套元素映射为简单类型的类字段.例如:

I am using JAXB-impl. I need to be able to map nested elements to class fields as simple types. For example:

<mapping>

    <search>
        <channel>main-channel</channel>
        <url>my-channel-url</url>
    </search>

    <items>
        <item>first</item>
        <item>second</item>
        <item>third</item>
    </items>

</mapping>

假设我需要将"url"标签绑定到类中的字段,这将不起作用(当然):

Assuming I need to bind "url" tag to a field in the class, this will not work (of course):

class Mapping{

    @XmlElement
    private String url;
}

@XmlElementWrapper,仅适用于集合.我看过一些有关使用Eclipse MOXy的帖子,并使用@XmlPath,但这不是一个选择.它必须是JAXB-impl.

@XmlElementWrapper, is for collections only. I have seen some post about using eclipse MOXy, and utilize @XmlPath, but this is not an option. It has to be JAXB-impl.

供参考: http://wiki.eclipse.org/EclipseLink/Examples /MOXy/XPath#Marshal_to_XML_-_MOXy_Customization_.231_-_Grouping_Element

是否有一种无需创建这些额外的嵌套类即可获取此映射的方法?

Is there a way to get this mapping without having to create these extra nested classes ?

推荐答案

具有附加的类Search,但是该类是私有嵌套类,并且不在Mapping类之外使用.
Mapping的公共API按预期返回url

With additional class Search, but this class is private nested class, and not used outside of Mapping class.
public API of class Mapping returns url as expected

@XmlAccessorType(XmlAccessType.FIELD)
class Mapping
{
   @XmlAccessorType(XmlAccessType.FIELD)
   private static class Search
   {
      private String channel;
      private String url;
   }

   private Search search;

   public String getUrl()
   {
      return search == null ? null : search.url;
   }
}

这篇关于JAXB绑定嵌套元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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