【问题标题】:XML Marshalling: How to add an attribute from another namespace to an elementXML Marshalling:如何将另一个命名空间中的属性添加到元素
【发布时间】:2010-08-23 21:05:37
【问题描述】:

我想生成这个 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 中完成此操作(仅供参考:我正在使用它在 Java 中将对象编组为 XML,使用 JiBX)。

【问题讨论】:

    标签: java xml xsd marshalling jibx


    【解决方案1】:

    假设当您说 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 示例

    我的元素类型

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

    困难部分

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

    【讨论】:

      猜你喜欢
      • 2013-09-21
      • 1970-01-01
      • 1970-01-01
      • 2019-07-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-17
      • 2021-06-28
      相关资源
      最近更新 更多