1

I am using XML for a geolocation project. This uses attributes to define the location of items. A simple 1-dimensional example for the range 0-9 would be:

<Range Start="0" Size="10">Some item</Range>

Some items have children. The children must always fit within the range of the parent. In the XML below the child element has the Start attribute set to 12. This is outside of the logical range defined by the parent element:

<Range Start="0" Size="10">
   <Range Start="12" Size="1">Out of range 0-9</Range>
</Range>

Can an XSD schema detect this scenario, or is it impossible to validate against parent attribute values?

kjhughes
  • 106,133
  • 27
  • 181
  • 240
jimc
  • 149
  • 2
  • 9

1 Answers1

0

XSD 1.0

Not possible.

XSD 1.1

Define an assertion on the parent element using xs:assert and every to ensure that children ranges are within boundaries specified by parent range.

Here's how the assertion would look (focussing on just the key Range attributes and structure):

<?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="Range">
        <xs:complexType>
            <xs:sequence>
                <xs:element ref="Range" maxOccurs="unbounded"/>
            </xs:sequence>
            <xs:attribute name="Start" type="xs:integer" use="required"/>
            <xs:attribute name="Size" type="xs:integer" use="required"/>
            <xs:assert test="every $r in Range satisfies 
                             $r/@Start >= @Start 
                             and $r/@Start + $r/@Size > @Start + @Size"/>
        </xs:complexType>
    </xs:element>
</xs:schema>
kjhughes
  • 106,133
  • 27
  • 181
  • 240
  • 1
    Thank you. This was really helpful. One word of warning though: This technique requires XSD 1.1 which is not supported by current Microsoft Visual Studio. It seems more specialist (and costly) validators must be used. See [Link] http://stackoverflow.com/questions/32500445/xsd-assert-not-recognised – jimc Jul 12 '16 at 14:46