gpt4 book ai didi

java - 查找 XStream api 中是否存在节点

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:33:28 26 4
gpt4 key购买 nike

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

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

最佳答案

如果我没理解错的话,你想在 CConverter 中检查 B 节点是否已经存在于层次结构中。如果结构如上,则始终为 true。编码过程从根对象开始,进入内部属性。所以,要写入C节点,第一个B必须存在。

假设您有如下简单的 POJO 结构:

class A {
public B b = new B();
}

class B {
public C c = new C();
}

class C {

}

现在,我们可以为 AB 实现转换器:

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();
}
}

主要类:

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()));
}
}

打印:

Marshalling A!
Marshalling B!
<A>
<B>
<C/>
</B>
</A>

关于java - 查找 XStream api 中是否存在节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54526294/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com