Restrict XSD attribute value based on another attribute value
Asked Answered
C

2

6

I have this in the XML:

<Const Name="a" Value="1.0"/>
<Const Name="b" Value="1"/>
<Const Name="c" Value="A"/>
<Const Name="d" Value="B"/>

I have these two cases:

  • For a Const element with Name="b" the Value must be one of 1, 2, 3 or 4. No other values are allowed.
  • Other Const elements may contain other values, as shown.

How do I express that in XSD?

So far I have this:

<xs:element name="Const">
   <xs:complexType>
       <xs:attribute name="Value" type="xs:string" use="required"/>
       <xs:attribute name="Name" type="xs:string" use="required"/>
   </xs:complexType>
</xs:element>

I use XSD 1.0, it seems: VS2013... so "Alternative" does not work for me... sadly...

Caffey answered 6/5, 2015 at 20:10 Comment(0)
M
13

You can do this using XSD 1.1's Conditional Type Assignment:

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
  xmlns:vc="http://www.w3.org/2007/XMLSchema-versioning"
  elementFormDefault="qualified"
  vc:minVersion="1.1"> 

  <xs:element name="Const">
    <xs:alternative test="@Name = 'a'" type="aType"/>        
    <xs:alternative                    type="otherType"/>
  </xs:element>

  <xs:complexType name="aType">
    <xs:sequence/>
      <xs:attribute name="Name" type="xs:string"/>
      <xs:attribute name="Value">
        <xs:simpleType>
          <xs:restriction base="xs:integer">
            <xs:minInclusive value="1"/>
            <xs:maxInclusive value="4"/>
          </xs:restriction>
        </xs:simpleType>
      </xs:attribute>
  </xs:complexType>

  <xs:complexType name="otherType">
    <xs:sequence/>
    <xs:attribute name="Name" type="xs:string"/>
    <xs:attribute name="Value" type="xs:string"/>
  </xs:complexType>
</xs:schema>
Metz answered 6/5, 2015 at 23:47 Comment(2)
for your aType I came up with this:<xs:simpleType name="DC1234"> <xs:restriction base="xs:string"> <xs:pattern value="[1234]" /> </xs:restriction> </xs:simpleType>Caffey
Yes, basing aType on regular expressions is perfectly valid too.Metz
H
4

Example solution ussing xs:assert supposing you're using XSD 1.1:

<xs:element name="Const">
    <xs:complexType>
        <xs:attribute name="Value" type="xs:string" use="required"/>
        <xs:attribute name="Name" type="xs:string" use="required"/>
        <xs:assert test="(@Name='b' and @Value=('1', '2', '3', '4'))
            or
            (@Name='a' and @Value=('1.0', '2.0', '3.0', '4.0'))
            or
            (@Name='c')
            or
            (@Name='d')"></xs:assert>
    </xs:complexType>
</xs:element>

Note that this is just a example and maybe you have to change it.

Hunter answered 6/5, 2015 at 21:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.