views:

34

answers:

1

I want to generate this XML:

<myElement myAttribute="whateverstring" xsi:type="hardPart"/>

I have this 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>

How exactly can I accomplish this in my XSD (FYI: I am using it to marshall objects into XML in Java, using JiBX).

A: 

Assuming when you say xsi:type, you mean the "type" attribute from the "http://www.w3.org/2001/XMLSchema-instance" namespace. It is not something that you add to your XML schema, it is a reserved means of qualifying an element (similar to a cast in Java).

For the following to be valid:

<myElement myAttribute="whateverstring" xsi:type="hardPart"/> 

You would need to have an XML schema like:

<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>

Then when your XML binding solution marshals an object corresponding to the type "hardPart" it may represent it as:

<myElement myAttribute="whateverstring" xsi:type="hardPart"/> 

Since myElement corresponds to the super type "myElementType", and needs to be qualified with xsi:type="hardPart" to represent that the content actually corresponds to the subtype "hardPart".

JAXB Example

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 {

}

Demo

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);
    }
}
Blaise Doughan