2013-06-24 26 views
1

关于jaxb抽象类型以及关联XML文档的使用,XML文档不能包含对抽象类型的引用 - 也就是说,XML必须使用具体类型。创建一个XSD来处理抽象类型

实施例(从here截取):

无效: <运输的xmlns = “http://cars.example.com/schema”/>

有效: <运输的xmlns =“HTTP ://cars.example.com/schema“xmlns:xsi =”http://www.w3.org/2001/XMLSchema-instance“xsi:type =”Car“/>

(其中传输是抽象的)

问:c我指示Jaxb解除封装,使其适当地包含/填充“xsi:type”值?

顺便说一下,我所有的jaxb类都在相同的包中,并且我的JaxbContext是针对此包进行配置的。

回答

1

你可以做到以下几点:

汽车

@XmlType注解可以用来指定类型名称。

import javax.xml.bind.annotation.XmlType; 

@XmlType(name="Car") 
public class Car { 

} 

演示

每当Java类型的XML元素是Object那么你的JAXB实现将有资格与xsi:type属性的元素。下面我们将利用JAXBElement这个实例。

import javax.xml.bind.*; 
import javax.xml.namespace.QName; 

public class Demo { 

    public static void main(String[] args) throws Exception { 
     JAXBContext jc = JAXBContext.newInstance(Car.class); 

     Car car = new Car(); 
     JAXBElement<Object> jaxbElement = new JAXBElement(new QName("transport"), Object.class, car); 

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

} 

输出

下面是从运行演示代码的输出。

<?xml version="1.0" encoding="UTF-8" standalone="yes"?> 
<transport xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="Car"/>