JAXB体验之旅第二篇:unmarshal

本文探讨了在使用JAXB进行unmarshal时遇到的@XmlElementRoot注解缺失的问题。当JAXB编译器未自动添加此注解时,可以通过手动添加或者启用XJC的'简单思维绑定模式'进行优化解决。此外,还提供了解决不需要@XmlElementRoot注解的marshal操作的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 今天研究了unmarshal,说白了其实就是xml文档读操作。其中遇到一个Unmarshaller.unmarshal方法返回实际对象的类型问题。起初个人一直觉得应该返回xml文档根元素类型的实例,通过实例操作发现不仅其然。
例子1:
xml schema:
<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element name="book">
   <xsd:complexType>
       <xsd:sequence>
       <xsd:element name="name" type="xsd:string"/>
      <xsd:element name="author" type="xsd:string"/>      
      <xsd:element name="ISBN" type="xsd:int"/>
      <xsd:element name="publisher" type="xsd:string"/>
      <xsd:element name="edition" type="xsd:int"/>
      <xsd:element type="xsd:double" name="price"/>
       </xsd:sequence>
    </xsd:complexType>
</xsd:element>
</xsd:schema>
对应xml 文档:
<?xml version="1.0" encoding="UTF-8"?>
<book xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="src/simple.xsd">
  <name>hello china</name>
  <author>owen</author>
  <ISBN>1860</ISBN>
  <publisher>objectiva</publisher>
  <edition>1</edition>
  <price>10.0</price>
</book>
解析类:
       
        /*************************the code can make sure the root element of XML document automatically
        JAXBContext context = JAXBContext.newInstance("com.objectiva.JAXBTesting.book");

        Unmarshaller unMarshaller = context.createUnmarshaller();
        Object object = unMarshaller.unmarshal(new File("simple.xml"));
       
        if(object instanceof Book)
        {
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值