反序列化许多子节点以添加对对象xStream java的引用

时间:2012-10-30 15:13:58

标签: java xstream

您好我要序列化以下图表:

<grafo>
 <nodo id="1">
   <child id="2"/>
 </nodo>
 <nodo id="2">
   <child id="3"/>
   <child id="4"/>
 </nodo>
 <nodo id="3">
   <child id="4"/>
 </nodo>
 <nodo id="4">
   <child id="1"/>
 </nodo>

我需要将子节点与图表List中其他节点的引用链接起来,这意味着在解组过程中我不能只创建一个新节点并使用给我读者的属性设置它的id,我需要它与图中已经存在的节点共享它的属性,以便能够做到这一点我尝试使用GraphConverter类中的以下函数:

public Object unmarshal(HierarchicalStreamReader reader,UnmarshallingContext arg1) {
    Grafo graph= new Grafo();
    ArrayList<ArrayList<String>> handlechilds= new ArrayList<ArrayList<String>>();
     while (reader.hasMoreChildren()) 
     {
         reader.moveDown();
         Nodo node= new Nodo(reader.getAttribute("id"));
         graph.nodos.add(node);
         reader.moveDown();
         //reader.getAttribute("id") ->> this just gives me the value of the fisrt node but not the anothers!!
         reader.moveUp();
         reader.moveUp();
     }
    return graph;
}

我正在考虑保存边缘的值并在另一个中添加引用,以便迭代图形,但我意识到当读者只返回其中一个孩子时,我需要所有这些。

1 个答案:

答案 0 :(得分:2)

在XStream中阅读Object references

xstream.setMode(XStream.ID_REFERENCES);