Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restrict XSD attribute value based on another attribute value

Tags:

xml

xsd

xsd-1.0

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"/>

Now only for Name="b" Const, the Value must be 1, 2, 3 or 4. No other values are allowed. Other Const 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...

like image 549
Erik Avatar asked May 06 '15 20:05

Erik


People also ask

How do I restrict attribute values in XML schema?

Restrictions on a Set of Values To limit the content of an XML element to a set of acceptable values, we would use the enumeration constraint. Note: In this case the type "carType" can be used by other elements because it is not a part of the "car" element.

What is complexType and simpleType in XSD?

XSD elements can be of type simpleType , complexType , or anyType . An element of type simpleType contains only text. It cannot have attributes and elements. An element of type complexType can contain text, elements, and attributes.

What is minOccurs and maxOccurs in XSD?

The minOccurs attribute specifies the minimum number of times that the element can occur. It can have a value of 0 or any positive integer. The maxOccurs attribute specifies the maximum number of times that the element can occur.

What is fixed attribute in XSD?

Fixed means the value in the XML document can only have the value specified in the XSD.


1 Answers

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>
like image 156
kjhughes Avatar answered Oct 05 '22 09:10

kjhughes