Create an XSD to handle abstract types
Regarding jaxb abstract types, and the consumption of associated XML documents, an XML document cannot contain a reference to the abstract type - that is, the XML must use the concrete type.
Example (taken from here):
Invalid: < transport xmlns="http://cars.example.com/schema"/>
Valid: < transport xmlns="http://cars.example.com/schema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="Car"/>
(where transport is abstract)
Q. How can i instruct Jaxb to unmarshall such that it includes / populates the "xsi:type" value appropriately?
Btw, all my jaxb classes are in then same package, and my JaxbContext is configured against this package.
You could do the following:
Car
The @XmlType
annotation can be used to specify the type name.
import javax.xml.bind.annotation.XmlType;
@XmlType(name="Car")
public class Car {
}
Demo
Whenever the Java type for an XML element is Object
then your JAXB implementation will qualify the element with the xsi:type
attribute. Below we will leverage an instance of JAXBElement
for this.
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);
}
}
Output
Below is the output from running the demo code.
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<transport xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="Car"/>
链接地址: http://www.djcxy.com/p/51714.html
上一篇: JAXB命名空间问题与扩展注释类的成员
下一篇: 创建一个XSD来处理抽象类型