JAXB display elements with an "unknown" name

I have XML that does not control how it is created. I want to create an object from it by parsing it into a class written by me.

One fragment of its structure is as follows:

<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 number of elements in the variable.

+4
source share
3 answers

If you use the following object model, then each of the unselected key_ # elements will be stored 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 corresponds to the classes associated with the @XmlRootElement annotation, then you can use @XmlAnyElement (lax = true), and the known elements will be converted to the corresponding objects. Example:

+5
source

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 the main method or so I would create an 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 the objects, I think that I would put all the elements inside the root element in a new xml file and write a class for this root element with the annotation @XmlRootElement .

Hope this helps, mman

0
source

Use as

  @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(); } } 
0
source

All Articles