我的XML
结构类似于以下内容。我有转换器来写入每个对象A
,B
和C
。是否可以在XStream
中检查XML层次结构中是否存在一个节点?即在以下情况下,如果我在写B
之前存在C
节点,我想做些什么。
<A>
<B>
<C>
</C>
</B>
</A>
答案 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()));
}
}