您可以更改模型并执行以下操作:
Root
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Root {
@XmlElement(name="parent")
List<Parent> allParents;
}
Parent
@XmlAccessorType(XmlAccessType.FIELD)
public class Parent {
@XmlElement(name="child")
List<Child> allChildren;
}
UPDATE
是否可以避开父类?
有几种不同的方法可以实现此目的:
选项 #1 - 使用 XmlAdapter 的任何 JAXB 实现
您可以使用 XmlAdapter 来虚拟添加Parent
class.
子适配器
import javax.xml.bind.annotation.adapters.XmlAdapter;
public class ChildAdapter extends XmlAdapter<ChildAdapter.Parent, Child> {
public static class Parent {
public Child child;
}
@Override
public Parent marshal(Child v) throws Exception {
Parent parent = new Parent();
parent.child = v;
return parent;
}
@Override
public Child unmarshal(Parent v) throws Exception {
return v.child;
}
}
Root
The @XmlJavaTypeAdapter
注释用于引用XmlAdapter
.
import java.util.List;
import javax.xml.bind.annotation.*;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Root {
@XmlElement(name="parent")
@XmlJavaTypeAdapter(ChildAdapter.class)
List<Child> allChildren;
}
Child
import javax.xml.bind.annotation.*;
@XmlAccessorType(XmlAccessType.FIELD)
public class Child {
@XmlAttribute
int id;
@XmlAttribute
String name;
}
选项 #2 - 使用 EclipseLink JAXB (MOXy)
如果您正在使用EclipseLink JAXB (MOXy)身为你的JAXB (JSR-222)实施然后你可以执行以下操作(注意:我是 MOXy 负责人):
Root
import java.util.List;
import javax.xml.bind.annotation.*;
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Root {
@XmlElement(name="parent")
List<Child> allChildren;
}
Child
MOXy's @XmlPath
注释的工作方式与您尝试使用的方式几乎相同@XmlElement
您帖子中的注释。
import javax.xml.bind.annotation.*;
import org.eclipse.persistence.oxm.annotations.XmlPath;
@XmlAccessorType(XmlAccessType.FIELD)
public class Child {
@XmlPath("child/@id")
int id;
@XmlPath("child/@name")
String name;
}
了解更多信息
- http://blog.bdoughan.com/2010/07/xpath-based-mapping.html
- http://blog.bdoughan.com/2011/05/specifying-eclipselink-moxy-as-your.html