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:
For this simple element, I would create a class called Categories:
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Categories {
protected String key_0;
protected String key_1;
protected String key_2;
public String getKey_0() {
return key_0;
}
public void setKey_0(String key_0) {
this.key_0 = key_0;
}
public String getKey_1() {
return key_1;
}
public void setKey_1(String key_1) {
this.key_1 = key_1;
}
public String getKey_2() {
return key_2;
}
public void setKey_2(String key_2) {
this.key_2 = key_2;
}
}
Then in a main method or so, I'd create the unmarshaller:
JAXBContext context = JAXBContext.newInstance(Categories.class);
Unmarshaller um = context.createUnmarshaller();
Categories response = (Categories) um.unmarshal(new FileReader("my.xml"));
// access the Categories object "response"
To be able to retrieve all objects, I think I would put all elements inside a root element in a new xml file and write a class for this root element with the @XmlRootElement
annotation.
Hope that helps, mman
Use like this
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public static class Categories {
@XmlAnyElement
@XmlJavaTypeAdapter(ValueAdapter.class)
protected List<String> categories=new ArrayList<String>();
public List<String> getCategories() {
return categories;
}
public void setCategories(String value) {
this.categories.add(value);
}
}
class ValueAdapter extends XmlAdapter<Object, String>{
@Override
public Object marshal(String v) throws Exception {
// write code for marshall
return null;
}
@Override
public String unmarshal(Object v) throws Exception {
Element element = (Element) v;
return element.getTextContent();
}
}
来源:https://stackoverflow.com/questions/4278546/jaxb-mapping-elements-with-unknown-name