如何对不是集合的节点进行隐式?

时间:2014-10-27 09:08:58

标签: java xml xstream

我想在此类型的xml文件中转换此类。如何删除节点<с>?如何使隐式节点不是集合?

爪哇:

public class root {
    int a;
    int b;
    int d;
}

XML:

<root>
  <a>123</a>
  <b>345</b>
  <c>
     <d>567</d>
  </c>
</root>

1 个答案:

答案 0 :(得分:0)

您可以尝试使用Converter。 创建一个实现com.thoughtworks.xstream.converters.Converter的类,并覆盖其marshal和unmarshal方法:添加一个用于此目的的丑陋示例。

class SimpleConverter implements Converter{
@Override
    public void marshal(Object o, HierarchicalStreamWriter writer, MarshallingContext marshallingContext) {
        Root i = (Root) o;
        writer.startNode("a");
        writer.setValue(String.valueOf(i.a));
        writer.endNode();
        writer.startNode("b");
        writer.setValue(String.valueOf(i.b));
        writer.endNode();
        writer.startNode("c");
        writer.startNode("d");
        writer.setValue(String.valueOf(i.d));
        writer.endNode();
        writer.endNode();

    }
@Override
    public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext unmarshallingContext) {
        Root root = new Root();
        reader.moveDown();
        root.a = Integer.valueOf(reader.getValue());
        reader.moveUp();
        reader.moveDown();
        root.b = Integer.valueOf(reader.getValue());
        reader.moveUp();
        reader.moveDown();
        reader.moveDown();
        root.d = Integer.valueOf(reader.getValue());
        reader.moveUp();
        reader.moveUp();
        return root;
    }
    @Override
    public boolean canConvert(Class aClass) {
        return aClass.equals(Root.class);
    }
}

class Root {
    public int a;
    public int b;
    public int d;
}

像这样使用:

        Root root = new Root();
        root.a = 1;
        root.b = 2;
        root.d = 3;
        XStream xStream = new XStream();
        xStream.registerConverter(new SimpleConverter());
        System.out.println(xStream.toXML(root));
        Root root1 = (Root) xStream.fromXML(xStream.toXML(root));