使用XStream进行解析 - 空标记和集合

时间:2013-10-23 06:35:56

标签: java xml-parsing xstream

我正在使用XStream将XML转换为域对象,并且遇到了问题。省略一些细节,XML看起来像这样:

<airport>
    <flights>
        <flight>.....</flight>
        <flight>.....</flight>
        <flight>.....</flight>
    </flights>
</airport>

可以有0到N flight个元素。飞行元素本身包含其他元素。我已经为机场,航班和航班创建了类,并使用xstream.alias函数注册了它们。

xstream = new XStream();
xstream.alias("airport", AirportPojo.class);
xstream.alias("flights", FlightsPojo.class);
xstream.alias("flight", FlightPojo.class);
xstream.useAttributeFor(AirportPojo.class, "flights");
xstream.addImplicitCollection(FlightsPojo.class, "flights", FlightPojo.class);
AirportPojo airportPojo = (AirportPojo) xstream.fromXML(xml);

因此,转换后,这会给我一个包含FlightsPojo对象的AirportPojo对象,该对象包含一组FlightPojo对象。但是,当有0个飞行元素时,FlightPojos的集合似乎是null。我希望(并且更喜欢)列表被初始化但其中包含零元素。我怎么能做到这一点?请记住,我不能使用注释,因为这是一个遗留项目。

2 个答案:

答案 0 :(得分:1)

如何实现自定义转换器?

class FlightsConverter implements Converter {
    @Override
    public boolean canConvert(Class clazz) {
        return clazz.equals(FlightsPojo.class);
    }

    @Override
    public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
        FlightsPojo flightsPojo = new FlightsPojo();
        flightsPojo.setFlights(new ArrayList<FlightPojo>());
        while (reader.hasMoreChildren()) {
            reader.moveDown();
            FlightPojo flightPojo = (FlightPojo) context.convertAnother(flightsPojo, FlightPojo.class);
            flightsPojo.getFlights().add(flightPojo);
            System.out.println(reader.getValue());
            reader.moveUp();
        }
        return flightsPojo;
    }

    @Override
    public void marshal(Object value, HierarchicalStreamWriter writer, MarshallingContext context) {
        // todo...
    }
}

然后像这样挂钩:

    XStream xstream = new XStream();
    xstream.registerConverter(new FlightsConverter());
    xstream.alias("airport", AirportPojo.class);
    xstream.alias("flights", FlightsPojo.class);
    xstream.alias("flight", FlightPojo.class);
    xstream.useAttributeFor(AirportPojo.class, "flights");
    AirportPojo airportPojo = (AirportPojo) xstream.fromXML(xml);

希望这会有所帮助;)

答案 1 :(得分:0)

看起来XStream无法以这种方式处理隐式集合。 See this part of XStream's FAQ.