带有变量属性的XSD元素

时间:2015-10-24 01:21:50

标签: xml xsd

从以下定义开始:

<xs:element name="Credentials">
    <xs:complexType>
      <xs:attribute name="accountID" type="xs:string" use="required"/>
      <xs:attribute name="username" type="xs:string" use="required"/>
      <xs:attribute name="password" type="xs:string" use="required"/>
      <xs:attribute name="cred1" type="xs:string"/>
      <xs:attribute name="cred2" type="xs:string"/>
      <xs:attribute name="cred3" type="xs:string"/>
      <xs:attribute name="cred4" type="xs:string"/>
      <xs:attribute name="cred5" type="xs:string"/>
      <xs:attribute name="cred6" type="xs:string"/>
      <xs:attribute name="cred7" type="xs:string"/>
      <xs:attribute name="cred8" type="xs:string"/>
      <xs:attribute name="cred9" type="xs:string"/>
      <xs:attribute name="cred10" type="xs:string"/>
      <xs:attribute name="cred11" type="xs:string"/>
      <xs:attribute name="cred12" type="xs:string"/>
      <xs:attribute name="cred13" type="xs:string"/>
      <xs:attribute name="cred14" type="xs:string"/>
      <xs:attribute name="cred15" type="xs:string"/>
      <xs:attribute name="cred16" type="xs:string"/>
      <xs:attribute name="cred17" type="xs:string"/>
      <xs:attribute name="cred18" type="xs:string"/>
      <xs:attribute name="cred19" type="xs:string"/>
      <xs:attribute name="cred20" type="xs:string"/>
    </xs:complexType>

如何将其更改为:

<xs:element name="Credentials">
    <xs:complexType>
      <xs:attribute name="accountID" type="xs:string" use="required"/>
      <xs:attribute name="username" type="xs:string" use="required"/>
      <xs:attribute name="password" type="xs:string" use="required"/>
      <!-- 0 or more of these attributes below - even 100 but I doubt I would need 100 for anything - i.e. optional -->
      <xs:attribute name=don't care, but it should have a name" type="xs:string"/>
    </xs:complexType>

验证此类有效数据:

<Credentials accountID="abc" username="me" password="mine"/>
<Credentials accountID="abc" username="me" password="mine" foo="bar"/>
<Credentials accountID="abc" username="me" password="mine" apples="oranges" fruit="sweet" just="another attribute"/>

1 个答案:

答案 0 :(得分:2)

如果您想允许任何属性,请使用xs:anyAttribute

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">

  <xs:element name="Credentials">
    <xs:complexType>
      <xs:attribute name="accountID" type="xs:string" use="required"/>
      <xs:attribute name="username" type="xs:string" use="required"/>
      <xs:attribute name="password" type="xs:string" use="required"/>
      <xs:anyAttribute processContents="skip"/>
    </xs:complexType>
  </xs:element>

</xs:schema>

processContents

  • 使用skip允许任何属性,忽略任何声明。
  • 使用lax允许任何属性,但需要声明验证 属性。
  • 使用strict仅允许声明的属性进行验证 成功。