简体   繁体   中英

Restrict Element Values Based on Attribute

I want to restrict the type of an Element based on the value of an Attribute, like this:

<Data type="decimal"> 44.00 </Data>

<Data type="date"> 2008-02-01 </Data>

Can a Schema be defined that does this?

It's a well known fact that, XML-Schema can't do this,

validation of an element based on the other element is treated as ambiguous, so not possible. But if you want, you can validate both type of data-types ignoring the conditional validation, something like this:

Define a new data type with custom name, and copy paste the pattern written below.

  <xs:simpleType name="new_type">
    <xs:restriction base="xs:string">
      <xs:pattern value="(([0-9]+)[.]([0-9]+))|(([0][1-9]|[1][0-2])/([0][1-9]|[1-2][0-9]|[3][0-1])/[1-2][0-9][0-9][0-9])"/>
    </xs:restriction>
  </xs:simpleType>

This will accept the Data of type decimal or date, but you cannot validate it with the attribute values,

The alternative solution is to use Schematron, but you won't get so handy and user-friendly tool for that as you get in-case of XSD and XSLT.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM