如何使用 JAXB 解组重复的嵌套类? [英] How to unmarshall repeated nested classes with JAXB?
问题描述
我如何指示 JAXB 处理这个?
How can I instruct JAXB to process this ?
XML
<root>
<parent>
<child id="1" name="foo" />
</parent>
<parent>
<child id="3" name="foo2" />
</parent>
<parent>
<child id="4" name="bar2" />
</parent>
<parent>
<child id="2" name="bar" />
</parent>
</root>
Root.java
@XmlRootElement
public class Root {
@XmlElement(name="parent/child")
List<Child> allChildren;
}
这不起作用...... allChildren 是空的.
This doesn't work ... allChildren is empty.
推荐答案
您可以更改模型并执行以下操作:
You could change your model and do the following:
根目录
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Root {
@XmlElement(name="parent")
List<Parent> allParents;
}
父母
@XmlAccessorType(XmlAccessType.FIELD)
public class Parent {
@XmlElement(name="child")
List<Child> allChildren;
}
<小时>
更新
是否可以避免父类?
有几种不同的方法可以实现这一点:
There are a couple of different ways to accomplish this:
选项 #1 - 使用 XmlAdapter 的任何 JAXB 实现
您可以使用 XmlAdapter 虚拟添加 Parent
类.
You could use an XmlAdapter to virtually add in the 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;
}
}
根目录
@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;
}
儿童
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 领导):
If you are using EclipseLink JAXB (MOXy) as your JAXB (JSR-222) implementation then you could do the following (Note: I'm the MOXy lead):
根目录
import java.util.List;
import javax.xml.bind.annotation.*;
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Root {
@XmlElement(name="parent")
List<Child> allChildren;
}
儿童
MOXy 的 @XmlPath
注释与您尝试在帖子中使用 @XmlElement
注释的方式非常相似.
MOXy's @XmlPath
annotation works pretty much the way you are trying to use the @XmlElement
annotation in your post.
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
这篇关于如何使用 JAXB 解组重复的嵌套类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!