1

对于这种简单的xml,有没有办法使用单个java bean进行映射:

<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 的情况下访问内部元素的属性?

4

2 回答 2

1

您可以使用XmlAdapter

父标识符适配器

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;
}
于 2012-09-12T17:15:01.610 回答
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;
    }
}
于 2012-09-12T15:23:00.037 回答