Content restriction and attribute validation on th

2019-04-24 06:38发布

问题:

I would like to validate that an element 'Test' should

  • Have its content restricted (for example, using a pattern restriction), and
  • Contain certain attributes (for example, 'id', 'class' and 'name').

The XSD I'm writing looks like this:

<xsd:element name="Test" minOccurs="0" maxOccurs="unbounded">
  <xsd:complexType mixed="true">
    <xsd:simpleContent>
      <xsd:restriction>
        <xsd:pattern value="xyz"/>
      </xsd:restriction>
    </xsd:simpleContent>
    <xsd:attribute name="id" type="xsd:string"></xsd:attribute>
    <xsd:attribute name="class" type="xsd:string"></xsd:attribute>
    <xsd:attribute name="name" type="xsd:string"></xsd:attribute>
  </xsd:complexType>
</xsd:element>

However, when I code this in Visual Studio, I get the following error on the 'xsd:attribute' elements:

'attribute' and content model are mutually exclusive

Is there a way to validate both a content restriction and attributes on the same element?

回答1:

You need to separate out your restriction and give it a name, then refer to it as a base type for an extension. Like this:

  <xsd:simpleType name="RestrictedString">
    <xsd:restriction base="xsd:string">
      <xsd:pattern value="xyz" />
    </xsd:restriction>
  </xsd:simpleType>
  <xsd:element name="Test">
    <xsd:complexType>
      <xsd:simpleContent>
        <xsd:extension base="RestrictedString">
          <xsd:attribute name="id" type="xsd:string" />
          <xsd:attribute name="class" type="xsd:string" />
          <xsd:attribute name="name" type="xsd:string" />
        </xsd:extension>
      </xsd:simpleContent>
    </xsd:complexType>
  </xsd:element>