Xstream 映射“选择"XML 元素 [英] Xstream to map "choice" elements of XML

查看:53
本文介绍了Xstream 映射“选择"XML 元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用 XStream 将受 XSD 约束的 XML 映射到 Java 对象.XSD 有 4 个复杂类型元素,它们是选择"元素,即这 4 个元素之一可以出现在 XML 中的根标记下.

I need to map an XML, constrained by an XSD to Java object using XStream. The XSD has 4 complex type elements, which are "choice" elements, that is either one of those 4 can be present in the XML under a root tag.

我一直在研究 XStream,但在我看来,要映射这样的 XML,我需要 8 个类.如何?这是……

I have been looking at XStream but it seems to me that, to map such an XML, I would require 8 classes. How? here it is...

例如,我的根元素是 VEHICLE,XML 中的每个复杂类型都是 a) CAR b) BIKE c) TRUCK d) TRACTOR.它们中的每一个都具有不同的属性.要将其映射到 Xstream 并使 XML(由 XStream 生成)符合 XSD,我们需要 8 个类,即.VehicleCarWrapper ->(有)CarVehicleTruckWrapper ->(有)卡车VehicleBikeWrapper ->(有)自行车VehicleTractorWrapper ->(有)拖拉机.

Say for example my root element is VEHICLE and each of the complex types in the XML are a) CAR b) BIKE c) TRUCK d) TRACTOR. Each of them have differing properties within them. To map this to Xstream and make the XML (generated by XStream) XSD compliant, we would need 8 classes viz. VehicleCarWrapper -> (has a) Car, VehicleTruckWrapper -> (has a) Truck, VehicleBikeWrapper -> (has a) Bike and VehicleTractorWrapper -> (has a) Tractor.

除了破旧的解决方案之外,还有人有什么建议吗?Xstream 中有没有办法映射 XML 根的这种选择"元素?因此,所有 4 个(即卡车、汽车、自行车、拖拉机)都可以作为关联实体进入 Wrapper,但 XStream 始终忽略除一个关联之外的所有关联,因此创建符合 XSD 的 XML.

Does anyone have a suggestion apart from the shabby solution? Is there a way in Xstream to map such a "choice"d element of the XML root? So as that, All the 4 (viz. Truck, Car, Bike, Tractor) can go into the Wrapper as associated entities, but XStream ignores all but one association at all times and hence creates an XSD compliant XML.

希望我的问题很清楚.

非常感谢!

推荐答案

为什么不改用 JAXB:

Why not use JAXB instead:

@XmlRootElement
public class Foo {
    @XmlElements(
        @XmlElement(name="car", type=Car.class),
        @XmlElement(name="bike", type=Bike.class),
        @XmlElement(name="truck", type=Truct.class),
        @XmlElement(name="tractor", type=Tractor.class)
    )
    public Vehicle vehicle;
}

JAXB & 的比较XStream 见:

For a comparison of JAXB & XStream see:

这篇关于Xstream 映射“选择"XML 元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆