假设当您说 xsi:type 时,您的意思是“ http://www.w3.org/2001/XMLSchema-instance ”命名空间中的“type”属性。它不是您添加到 XML 模式中的东西,它是限定元素的保留方法(类似于 Java 中的强制转换)。
为使以下内容有效:
<myElement myAttribute="whateverstring" xsi:type="hardPart"/>
您需要有一个 XML 模式,例如:
<xsd:element name="myElement" type="myElementType"/>
<xsd:complexType name="myElementType">
<xsd:attribute name="myAttribute" type="xsd:boolean" />
</xsd:complexType>
<xsd:complexType name="hardPart">
<xsd:complexContent>
<xsd:extension base="myElementType">
...
</xsd:extension>
</xsd:complexContent>
</xsd:complexType>
然后,当您的 XML 绑定解决方案编组对应于“hardPart”类型的对象时,它可能将其表示为:
<myElement myAttribute="whateverstring" xsi:type="hardPart"/>
由于 myElement 对应超类型“myElementType”,需要用 xsi:type="hardPart" 限定,表示内容实际对应子类型“hardPart”。
JAXB 示例
我的元素类型
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class MyElementType {
private String myAttribute;
@XmlAttribute
public void setMyAttribute(String myAttribute) {
this.myAttribute = myAttribute;
}
public String getMyAttribute() {
return myAttribute;
}
}
硬零件
public class HardPart extends MyElementType {
}
演示
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.Marshaller;
import javax.xml.namespace.QName;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(HardPart.class, MyElementType.class);
HardPart hardPart = new HardPart();
hardPart.setMyAttribute("whateverstring");
JAXBElement<MyElementType> jaxbElement = new JAXBElement(new QName("myElement"), MyElementType.class, hardPart);
Marshaller marshaller = jc.createMarshaller();
marshaller.marshal(jaxbElement, System.out);
}
}