5

我有一个 XML 无法控制它的生成方式。我想通过将它解组到我手写的类来创建一个对象。

其结构的一个片段如下所示:

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

我该如何处理这种情况?当然,元素数量是可变的。

4

3 回答 3

7

如果您使用以下对象模型,则每个未映射的 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) 并且已知元素将转换为相应的对象。有关示例,请参见:

于 2010-11-25T18:41:13.207 回答
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();
          }
       }
于 2015-06-22T11:21:42.650 回答
-1

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

}

然后在一个主要方法中,我会创建解组器:

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注释为这个根元素编写一个类。

希望有帮助,mm

于 2010-11-25T15:53:59.273 回答