Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
311 views
in Technique[技术] by (71.8m points)

java - Access attribute of internal element in the most simple way

Is there any way to do mapping with single java bean for such simple xml:

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

I've tried something like this:

@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;
}

In other words - how can I access attribute of internal element without creating of corresponding bean?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You could use an 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;
    }

}

Item

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

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

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

If you are using EclipseLink MOXy as your JAXB provider then you could leverage the @XmlPath extension to do the following:

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

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...