查找XStream API中是否存在节点

时间:2019-02-05 00:31:10

标签: java xstream

我的XML结构类似于以下内容。我有转换器来写入每个对象ABC。是否可以在XStream中检查XML层次结构中是否存在一个节点?即在以下情况下,如果我在写B之前存在C节点,我想做些什么。

<A>
    <B>
        <C>
        </C>
    </B>
</A>    

1 个答案:

答案 0 :(得分:2)

如果我的理解正确,那么您想检查CConverter节点是否在层次结构中已经存在。如果结构如上,则始终为B。编组过程从根对象开始,进入内部属性。因此,要写入true节点,首先必须存在C

假设您具有简单的B结构,如下所示:

POJO

现在,我们可以为class A { public B b = new B(); } class B { public C c = new C(); } class C { } A实现转换器了:

B

class AConverter implements Converter { public boolean canConvert(Class clazz) { return clazz.equals(A.class); } public void marshal(Object value, HierarchicalStreamWriter writer, MarshallingContext context) { System.out.println("Marshalling A!"); A a = (A) value; if (a.b != null) { writer.startNode("B"); context.convertAnother(a.b); writer.endNode(); } } public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) { throw new NotImplementedException(); } } class BConverter implements Converter { public boolean canConvert(Class clazz) { return clazz.equals(B.class); } public void marshal(Object value, HierarchicalStreamWriter writer, MarshallingContext context) { System.out.println("Marshalling B!"); B b = (B) value; if (b.c != null) { writer.startNode("C"); context.convertAnother(b.c); writer.endNode(); } } public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) { throw new NotImplementedException(); } } 类:

Main

打印:

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import sun.reflect.generics.reflectiveObjects.NotImplementedException;

public class XStreamApp {
    public static void main(String[] args) {
        XStream xStream = new XStream();
        xStream.registerConverter(new AConverter());
        xStream.registerConverter(new BConverter());
        xStream.alias("A", A.class);

        System.out.println(xStream.toXML(new A()));
    }
}