以最简单的方式访问内部元素的属性

时间:2012-09-12 14:57:09

标签: java java-ee jaxb

有没有办法用单个java bean映射这样简单的xml:

<item lang="en">
   <item-url>some url</item-url>
   <parent id="id_123"/>
</item>

我尝试过这样的事情:

@XmlRootElement( name = "item" )
public class Item {

    @XmlElement( name = "item-url" )
    private String url;

    @XmlAttribute( name = "parent/@id" )
    // Of course XPath doesn't work here, but it would be great...
    private String parentId;
}

换句话说 - 如何在不创建相应bean的情况下访问内部元素的属性?

2 个答案:

答案 0 :(得分:1)

您可以使用XmlAdapter

<强> ParentIdAdapter

public class ParentIdAdapter extends XmlAdapter<ParentIdAdapter.AdaptedParentId, String> {

    public String unmarshal(AdaptedParentId value) {
        return value.id;
    }

    public AdaptedParentId marshal(String value) {
        AdaptedParentId adapted = new AdaptedParentId();
        adapted.id = value;
        return adapted;
    }

    public static class AdaptedParentId {
        @XmlAttribute
        public String id;
    }

}

<强>物品

@XmlRootElement( name = "item" )
public class Item {

    @XmlElement( name = "item-url" )
    private String url;

    @XmlElement( name = "parent" )
    @XmlJavaTypeAdapter(ParentIdAdapter.class)
    private String parentId;
}

如果您使用EclipseLink MOXy作为JAXB提供商,那么您可以利用@XmlPath扩展程序执行以下操作:

@XmlRootElement( name = "item" )
public class Item {

    @XmlElement( name = "item-url" )
    private String url;

    @XmlPath("parent/@id")
    private String parentId;
}

答案 1 :(得分:0)

由于我不想在我的包中创建冗余类,我找到的最佳解决方案是:

@XmlRootElement( name = "item" )
public class Item {

    @XmlRootElement( name = "parent" )
    private static class ParentIdWrapper {
        @XmlAttribute( name = "id" )
        public String id;
    }

    @XmlElement( name = "item-url" )
    private String url;

    @XmlElement( name = "parent" )
    private ParentIdWrapper parentIdWrap;

    public String getParentId() {
        return this.parentIdWrap.id;
    }
}