你可以改變你的模型,並做到以下幾點:
根
@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;
}
UPDATE
是否有可能避免父類?
有幾種不同的方式來實現:
選項1 - 使用XmlAdapter
你可以使用一個XmlAdapter在Parent
類幾乎添加任何JAXB實現。
ChildAdapter
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(莫西)
如果您正在使用EclipseLink JAXB (MOXy)爲您JAXB (JSR-222)實現,那麼你可以做以下(注:我是MOXy的領導):
根
import java.util.List;
import javax.xml.bind.annotation.*;
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Root {
@XmlElement(name="parent")
List<Child> allChildren;
}
兒童
莫西的@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;
}
更多信息
是否有可能避免父類? – Stephan
+1當我獨立地提出與該領域公認的專家完全相同的解決方案時,總是令人放心:-) –
@IanRoberts - 我+也爲您解答了答案:)。 –