XStream如何处理重复的或循环引用?
表面上看,它是按照XStream的模式根据XPath节点顺序序列化对象,但实际上并不是像想象的那样,看下面的代码示例:
1. 创建重复循环对象CircularDesign
packagecom.favccxx.favsoft.pojo; publicclassCircularDesign{ privateStringname; privateCircularDesignduplicateDesign; publicCircularDesign(Stringname){ this.name=name; } publicCircularDesign(Stringname,CircularDesignduplicateDesign){ this.name=name; this.duplicateDesign=duplicateDesign; } publicStringgetName(){ returnname; } publicvoidsetName(Stringname){ this.name=name; } publicCircularDesigngetDuplicateDesign(){ returnduplicateDesign; } publicvoidsetDuplicateDesign(CircularDesignduplicateDesign){ this.duplicateDesign=duplicateDesign; } }
2. 代码测试
packagecom.favccxx.favsoft.main; importjava.util.ArrayList; importjava.util.List; importcom.favccxx.favsoft.pojo.CircularDesign; importcom.thoughtworks.xstream.XStream; publicclassSimpleCircularDesign{ publicstaticvoidmain(String[]args){ CircularDesigncd=newCircularDesign("circularnodes"); ListtreeList=newArrayList(); //添加两次CircularDesign treeList.add(cd); treeList.add(cd); //添加一次自身对象 treeList.add(treeList); XStreamxstream=newXStream(); xstream.alias("duplicateDesign",CircularDesign.class); System.out.println(xstream.toXML(treeList)); } }
3. 输出结果
<list> <duplicateDesign> <name>circularnodes</name> </duplicateDesign> <duplicateDesignreference="../duplicateDesign"/> <listreference=".."/> </list>
这是XStream根据W3C XPath规范中一个叫做的XPATH_RELATIVE_REFERENCES默认规则输出来的内容,这是完全按照人们读取内容的方式输出的。
这种输出方式是因为 XPath相对模式允许以任意形式的图文输出内容,XStream的默认输出模式如下:
xstream.setMode(XStream.XPATH_RELATIVE_REFERENCES);
4. 如果将XStream的输出模式改为绝对路径模式呢,好像没有比原来好多少。
xstream.setMode(XStream.XPATH_ABSOLUTE_REFERENCES); <list> <duplicateDesign> <name>circularnodes</name> </duplicateDesign> <duplicateDesignreference="/list/duplicateDesign"/> <listreference="/list"/> </list>
5. XStream还提供了一种ID引用模式,如下所示,不过结果好像并没有比原来增加多少可读性。
xstream.setMode(XStream.ID_REFERENCES); <listid="1"> <duplicateDesignid="2"> <name>circularnodes</name> </duplicateDesign> <duplicateDesignreference="2"/> <listreference="1"/> </list>
6. XStream还有单节点相对路径和单节点绝对路径模式,输出效果分别如下,是不是有种上面几种模式混合加身的效果。然而这有什么卵用呢,还是一样的没有可读性。
xstream.setMode(XStream.SINGLE_NODE_XPATH_RELATIVE_REFERENCES); <list> <duplicateDesign> <name>circularnodes</name> </duplicateDesign> <duplicateDesignreference="../duplicateDesign[1]"/> <listreference=".."/> </list>
xstream.setMode(XStream.SINGLE_NODE_XPATH_ABSOLUTE_REFERENCES); <list> <duplicateDesign> <name>circularnodes</name> </duplicateDesign> <duplicateDesignreference="/list[1]/duplicateDesign[1]"/> <listreference="/list[1]"/> </list>
7. XStream其实还提供了一种XPath无引用模式,将添加自身引用的代码去掉,并设置XPath模式即可。
//treeList.add(treeList); xstream.setMode(XStream.NO_REFERENCES);