2010-08-23 14 views
3

Je veux générer ce XML:XML sérialisation: Comment ajouter un attribut d'un autre espace de noms à un élément

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

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

Comment exactement puis-je accomplir cela en mon XSD (FYI: je l'utilise pour marshall objets en XML en Java, en utilisant JiBX).

Répondre

1

En supposant que vous dites xsi: type, vous voulez dire l'attribut "type" de l'espace de noms "http://www.w3.org/2001/XMLSchema-instance". Ce n'est pas quelque chose que vous ajoutez à votre schéma XML, c'est un moyen réservé de qualifier un élément (similaire à un cast en Java).

Pour ce qui suit pour être valide:

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

Vous devez avoir un schéma XML comme:

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

Puis, lorsque votre solution de liaison XML maréchaux un objet correspondant au type « hardPart "il peut le représenter comme:

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

Depuis myElement correspond au super ty pe "myElementType", et doit être qualifié avec xsi: type = "hardPart" pour représenter que le contenu correspond réellement au sous-type "hardPart".

JAXB Exemple

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