JAXB mapping elements with “unknown” name

蓝咒 提交于 2019-12-01 06:32:46

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:

mman

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();
          }
       }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!