![](/img/trans.png)
[英]How do I add a namespace attribute to an element in JAXB when marshalling?
[英]XML Marshalling: How to add an attribute from another namespace to an element
我想生成這個XML:
<myElement myAttribute="whateverstring" xsi:type="hardPart"/>
我有這個XSD:
<xsd:element name="myElement">
<xsd:complexType>
<xsd:attribute name="myAttribute" type="xsd:boolean" />
<!-- need to add the xsi:attribue here -->
</xsd:complexType>
</xsd:element>
我怎樣才能在我的XSD中實現這一點(僅供參考:我使用它來使用JiBX將對象編組為Java中的XML)。
假設您說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示例
MyElementType
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;
}
}
HardPart
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);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.