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

Categories

I have an XML which is out of my control on how it is generated. I want to create an object out of it by unmarshaling it to a class written by hand by me.

One snippet of its structure looks like:

<categories>
    <key_0>aaa</key_0>
    <key_1>bbb</key_1>
    <key_2>ccc</key_2>
</categories>

How can I handle such cases? Of course the element count of is variable.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.1k views
Welcome To Ask or Share your Answers For Others

1 Answer

If you use the following object model then each of the unmapped key_# elements will be kept as an instance of org.w3c.dom.Element:

import java.util.List;
import javax.xml.bind.annotation.XmlAnyElement;
import javax.xml.bind.annotation.XmlRootElement;
import org.w3c.dom.Element;

@XmlRootElement
public class Categories {

    private List<Element> keys;

    @XmlAnyElement
    public List<Element> getKeys() {
        return keys;
    }

    public void setKeys(List<Element> keys) {
        this.keys = keys;
    }

}

If any of the elements correspond to classes mapped with an @XmlRootElement annotation, then you can use @XmlAnyElement(lax=true) and the known elements will be converted to the corresponding objects. For an example see:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...