如何在 XSD 中为具有子元素序列的元素添加属性声明? [英] How to add attribute declaration in XSD for element with sequence of child elements?

查看:25
本文介绍了如何在 XSD 中为具有子元素序列的元素添加属性声明?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的示例 XML 代码:

This is my sample XML code:

<Address>
        <StreetAddress></StreetAddress>
        <OtherDestination />
        <City>TORONTO</City>
</Address>

当前正在使用此 XSD:

That is currently using this XSD:

<xs:element name="Address" nillable="true">
    <xs:complexType>
        <xs:sequence minOccurs="0">
            <xs:element ref="StreetAddress" minOccurs="0"/>
            <xs:element ref="OtherDestination" minOccurs="0"/>
            <xs:element ref="City" minOccurs="0"/>
        </xs:sequence>
    </xs:complexType>
</xs:element>

我想像这样向 Address 元素添加一个属性 id ..

I want to add an attribute id to Address element like this..

<Address id="first">
        <StreetAddress></StreetAddress>
        <OtherDestination />
        <City>TORONTO</City>
</Address>

我应该如何更改现有的 XSD 以满足我的要求?

How should I change the existing XSD to fulfill my requirement?

推荐答案

xs:complexType 中可以在 xs:sequence 之后添加属性声明:

An attribute declaration can be added within xs:complexType after the xs:sequence:

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" 
           elementFormDefault="qualified">
  <xs:element name="Address">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="StreetAddress" minOccurs="0" type="xs:string"/>
        <xs:element name="OtherDestination" minOccurs="0" type="xs:string"/>
        <xs:element name="City" minOccurs="0" type="xs:string"/>
      </xs:sequence>

      <!------------------------------------------>
      <!-- This is where to declare attributes: -->
      <xs:attribute name="id" type="xs:string"/>
      <!------------------------------------------>

    </xs:complexType>
  </xs:element>
</xs:schema>

上述 XSD 将成功验证您的 XML.

The above XSD will validate your XML successfully.

这篇关于如何在 XSD 中为具有子元素序列的元素添加属性声明?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆