繁体   English   中英

XML编组:如何将属性从另一个名称空间添加到元素

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM