XStream以外のものを使用することを検討したい場合は、EclipseLink JAXB (MOXy)は@XmlInverseReference(私はMOXy techリードです)で双方向プロパティを簡単に処理します。
あなたのオブジェクトモデルのようにマップされます:
import java.util.List;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Parent {
private List<Child> children;
@XmlElement(name="child")
public List<Child> getChildren() {
return children;
}
public void setChildren(List<Child> children) {
this.children = children;
}
}
と(親プロパティに@XmlInverseReferenceの使用を注意してください):
import org.eclipse.persistence.oxm.annotations.XmlInverseReference;
public class Child {
private Parent parent;
@XmlInverseReference(mappedBy="children")
public Parent getParent() {
return parent;
}
public void setParent(Parent parent) {
this.parent = parent;
}
}
デモコードは(input.xmlにようになります。あなたの質問からXMLを参照してください):
import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Parent.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
Parent parent = (Parent) unmarshaller.unmarshal(new File("input.xml"));
for(Child child : parent.getChildren()) {
System.out.println(child.getParent());
}
}
}
JAXB実装としてMOXyを指定するには次のエントリを使用してモデルクラスと同じパッケージでjaxb.propertiesと呼ばれるファイルが含ま:以下
javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory
はJAXBやXStreamのの私の比較へのリンクです:
これは良い考えではないかもしれないというあなたの意見に同意しますが、私はいくつかの外部の制約の下で動作しています。したがって、 'public class Child {プライベート親の親; } '。 XStreamはこれを自動的に入力しますか?これを処理するために設定する必要があるXStreamの注釈や設定は何ですか? – Freiheit
well - オブジェクトをマーシャリングするときに参照が設定されている場合、オブジェクトを非整列化するときにそのオブジェクトが設定されます。IIRCそれはちょうど起こる。それを試しましたか?それは私が正常に動作するかどうかを確認する方法です! – time4tea
それは時間がかかりません:System.out.println(new XStream()。toXML(parent)); – time4tea