简短:我想将XML文件解组为抽象元素列表。 我会提供一些简短的样本: XML:
<Container>
<Set>
<A x="1"/>
<B/>
<Set>
<C/>
<D x="3"/>
</Set>
<E/>
</Set>
</Container>
爪哇:
import java.io.File;
import java.util.List;
import javax.xml.bind.*;
import javax.xml.bind.annotation.*;
@XmlTransient
@XmlSeeAlso( {A.class, B.class, C.class, D.class, E.class, Set.class})
class Abs {
private String x;
public Abs() { x = null; }
public String getX() { return x; }
public void setX(String x) { this.x = x; }
}
@XmlRootElement(name = "A")
class A extends Abs { public A() {} }
@XmlRootElement(name = "B")
class B extends Abs { public B() {} }
@XmlRootElement(name = "C")
class C extends Abs { public C() {} }
@XmlRootElement(name = "D")
class D extends Abs { public D() {} }
@XmlRootElement(name = "E")
class E extends Abs { public E() {} }
@XmlRootElement(name = "Set")
class Set extends Abs {
private List<Abs> elements;
@XmlElementWrapper
@XmlAnyElement(lax=true)
public List<Abs> getElements() { return elements; }
public void setElements( List<Abs> elements ) {
this.elements = elements;
}
}
@XmlRootElement(name = "Container")
class Container {
Set main;
public Container() { this.main = null; }
@XmlElement(name = "Set")
Set getMain() { return main; }
void setMain(Set main) { this.main = main; }
}
public class Main {
public static void main(String[] args) {
try {
File file = new File("test.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(Container.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Container c = (Container) jaxbUnmarshaller.unmarshal(file);
System.out.println(c);
} catch (Exception e) {
e.printStackTrace();
}
}
}
我在打印线上有一个断点,此时,我的&#34; c&#34;有一个空列表。 我怎样才能让它发挥作用?
答案 0 :(得分:2)
由于elements属性的所有可能值都是Abs
的子类,我会使用@XmlElementRef
。
@XmlElementRef
public List<Abs> getElements() { return elements; }
@XmlAnyElement(lax=true)
会给您相同的行为,但会带来以下限制:
org.w3c.dom.Element
的实例被实例化,JAXB将尝试将其放入您的List
。@XmlAnyElement
映射该班级中的其他字段/媒体资源。答案 1 :(得分:1)
更改您的Set.java
...
import java.util.List;
import javax.xml.bind.annotation.XmlAnyElement;
public class Set extends Abs {
private List<Object> elements;
@XmlAnyElement(lax=true)
public List<Object> getElements() { return elements; }
public void setElements( List<Object> elements ) {
this.elements = elements;
}
}