gpt4 book ai didi

java - JAXB : how to read the xsi:type value when unmarshalling

转载 作者:数据小太阳 更新时间:2023-10-29 02:08:41 26 4
gpt4 key购买 nike

我在 XSD/XML 到 Java 的方向上使用 JAXB。我的 XSD 包含派生类型,我必须解码的 XML 包含 xsi:type 属性。查看代码 JAXB(默认的 Sun 实现)已经生成(用于解码)似乎没有方法来获取这些属性。

是不是因为我总能对解码的 Java 对象执行 getClass() 并找到实际的类?

不过,根据我提供给 JAXBContext.newInstance 的包或类,是否可以实例化一些基类? (一个是对应于 xsi:type 属性的实际值的类的父类(super class))。在这种情况下,可能需要能够读取 XML 实例中出现的实际属性的值。

最佳答案

JAXB (JSR-222)实现将为您处理一切。 JAXB 认为每个类对应一个复杂类型。它有一个计算类型名称的算法,但您可以使用 @XmlType 注释覆盖它。当一个元素被解码时,如果它包含一个 xsi:type 属性,那么 JAXB 将查看是否有与该类型关联的类。如果存在,它将实例化该类型的类,如果不存在,它将根据通过注释提供的映射元数据实例化与该元素对应的类型。

了解更多信息


更新

下面是一个可能有帮助的例子:

schema.xsd

在复杂类型 canadianAddress 下的 XML 架构中扩展了复杂类型 address

<?xml version="1.0" encoding="UTF-8"?>
<schema
xmlns="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.example.org/customer"
xmlns:tns="http://www.example.org/customer"
elementFormDefault="qualified">

<element name="customer">
<complexType>
<sequence>
<element name="address" type="tns:address"/>
</sequence>
</complexType>
</element>

<complexType name="address">
<sequence>
<element name="street" type="string"/>
</sequence>
</complexType>

<complexType name="canadianAddress">
<complexContent>
<extension base="tns:address">
<sequence>
<element name="postalCode" type="string"/>
</sequence>
</extension>
</complexContent>
</complexType>

</schema>

演示

在下面的演示代码中,XML 将转换为从上述 XML 模式生成的 JAXB 模型,然后再转换回 XML。

import java.io.File;
import javax.xml.bind.*;

public class Demo {

public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance("org.example.customer");

Unmarshaller unmarshaller = jc.createUnmarshaller();
File xml = new File("src/org/example/customer/input.xml");
Customer customer = (Customer) unmarshaller.unmarshal(xml);

Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(customer, System.out);
}

}

input.xml/输出

下面是 XML。 address 元素使用 xsi:type 进行限定,表明它拥有 canadianAddress 的实例,而不仅仅是一个 address.

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<customer xmlns="http://www.example.org/customer">
<address xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="canadianAddress">
<street>1 A Street</street>
<postalCode>Ontario</postalCode>
</address>
</customer>

关于java - JAXB : how to read the xsi:type value when unmarshalling,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16903618/

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