Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JAXB mapping elements with "unknown" name

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.

like image 659
bbcooper Avatar asked Nov 25 '10 15:11

bbcooper


1 Answers

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:

  • http://bdoughan.blogspot.com/2010/08/using-xmlanyelement-to-build-generic.html
like image 89
bdoughan Avatar answered Oct 18 '22 13:10

bdoughan