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

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

其结构的一个片段如下:

 aaa bbb ccc  

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

如果使用以下对象模型,则每个未映射的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 keys; @XmlAnyElement public List getKeys() { return keys; } public void setKeys(List keys) { this.keys = keys; } } 

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

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

像这样使用

  @XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) public static class Categories { @XmlAnyElement @XmlJavaTypeAdapter(ValueAdapter.class) protected List categories=new ArrayList(); public List getCategories() { return categories; } public void setCategories(String value) { this.categories.add(value); } } class ValueAdapter extends XmlAdapter{ @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(); } }