XML Marshalling: how to add an attribute from another namespace to an element

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 use it to sort objects in XML in Java using JiBX).

+3
source share
1 answer

Assuming you say xsi: type, you mean the “type” attribute from the http://www.w3.org/2001/XMLSchema-instance namespace . This is not what you add to your XML schema, it is a reserved tool for defining an element (similar to a cast in Java).

For correctness:

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

You will need an XML schema, for example:

<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);
    }
}
+1

Source: https://habr.com/ru/post/1761192/


All Articles