Restrict the attribute value and the value of the element using XSD

血红的双手。 提交于 2019-12-11 06:13:01

问题


I have a requirement where I need to restrict the attribute value and its element's value using an XSD. I've been able to restrict the attribute value to one of

JSON
SWAGGER

so far, but I also need to restrict the element value to one of

letter.c
di.js

as well.

XML:

<response src="XML">
  <resp name="JSON">letter.c</resp>
  <resp name="SWAGGER">di.js</resp>
</response>

XSD:

<xs:schema attributeFormDefault="unqualified"
          elementFormDefault="qualified"
          xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xs:element name="response">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="resp" maxOccurs="14" minOccurs="1">
                    <xs:complexType>
                        <xs:simpleContent>
                            <xs:extension base="respFilter">
                                <xs:attribute name="name" use="required" 
                                              type="Enum" />
                            </xs:extension>
                        </xs:simpleContent>
                    </xs:complexType>
                </xs:element>
            </xs:sequence>
            <xs:attribute name="src" use="required">
                <xs:simpleType>
                    <xs:restriction base="xs:string">
                        <xs:enumeration value="XML"></xs:enumeration>
                    </xs:restriction>
                </xs:simpleType>
            </xs:attribute>
        </xs:complexType>
    </xs:element>
    <xs:simpleType name="Enum">
        <xs:restriction base="xs:string">
            <xs:enumeration value="JSON">
            </xs:enumeration>
            <xs:enumeration value="SWAGGER">
            </xs:enumeration>
        </xs:restriction>
    </xs:simpleType>
    <xs:simpleType name="respFilter">
        <xs:restriction base="xs:string">
            <xs:minLength value="0"></xs:minLength>
            <xs:maxLength value="1064"></xs:maxLength>
        </xs:restriction>
    </xs:simpleType>
</xs:schema>

Is there a way I can restrict both of them using an XSD?


回答1:


Sure, just use xs:enum as you've done for the resp/@name attribute.

Replace

  <xs:simpleType name="respFilter">
    <xs:restriction base="xs:string">
      <xs:minLength value="0"></xs:minLength>
      <xs:maxLength value="1064"></xs:maxLength>
    </xs:restriction>
  </xs:simpleType>

with

<xs:restriction base="xs:string">
  <xs:maxLength value="1064"/>
  <xs:enumeration value="letter.c"/>
  <xs:enumeration value="di.js"/>
</xs:restriction>

Side notes:

  • Use self-closing tags to improve readability.
  • Your xs:minLength value="0" against a xs:string base was superfluous.


来源:https://stackoverflow.com/questions/46446944/restrict-the-attribute-value-and-the-value-of-the-element-using-xsd

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!