java xsi type_java – JAXB:如何在解组时读取xsi:type值

JAXB (JSR-222)实施将为您处理一切. JAXB认为每个类对应一个复杂类型.它有一个算法来确定类型名称,但您可以使用@XmlType注释覆盖它.如果元素是包含xsi:type属性的解组,则JAXB将查看是否存在与该类型关联的类.如果存在,它将实例化该类型的类,否则它将基于通过注释提供的映射元数据实例化与该元素对应的类型.

欲获得更多信息

UPDATE

以下是一个可能有用的示例:

schema.xsd

在复杂类型下面的XML模式中,canadianAddress扩展了complexType地址.

xmlns="http://www.w3.org/2001/XMLSchema"

targetNamespace="http://www.example.org/customer"

xmlns:tns="http://www.example.org/customer"

elementFormDefault="qualified">

演示

在下面的演示代码中,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的实例而不仅仅是一个地址.

1 A Street

Ontario

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值