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.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With