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