具有“未知”名称的JAXB映射元素

时间:2010-11-25 15:21:36

标签: java xml jaxb unmarshalling

我有一个XML,它无法控制它是如何生成的。我想通过将它解组为由我手工编写的类来创建一个对象。

其结构的一个片段如下:

<categories>
    <key_0>aaa</key_0>
    <key_1>bbb</key_1>
    <key_2>ccc</key_2>
</categories>

我该如何处理这类案件?当然,元素数量是可变的。

3 个答案:

答案 0 :(得分:5)

如果使用以下对象模型,则每个未映射的key_#元素将保留为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;
    }

}

如果任何元素对应于使用@XmlRootElement注释映射的类,则可以使用@XmlAnyElement(lax = true),并且已知元素将转换为相应的对象。有关示例,请参阅:

答案 1 :(得分:0)

对于这个简单的元素,我将创建一个名为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;
    }

}

然后在主方法中,我创建了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"

为了能够检索所有对象,我想我会将所有元素放在一个新的xml文件中的根元素中,并使用@XmlRootElement注释为这个根元素编写一个类。

希望有所帮助, MMAN

答案 2 :(得分:0)

像这样使用

        @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();
          }
       }
相关问题