Ichorus
Ichorus

Reputation: 4617

Is it possible to verify 'referential integrity' of xml data against an xsd?

Is it possible to verify 'referential integrity' of xml data against an xsd? Or is an xsd merely a data format definition.

If I have an xsd that defines a parent/child relationship does validation of an xml document against that xsd guarantee that the pre-requisite data for the relationship to be complete, exists?

For example, let's say I have a SCHOOL and a STUDENT. Every STUDENT must have a valid SCHOOL_ID. Let's say I have one SCHOOL defined with a SCHOOL_ID of '001' but a STUDENT defined with SCHOOL_ID of '002' but that SCHOOL_ID doesn't exist under SCHOOL. Will that xml document's validation against the xsd that defines that required relationship fail?

Upvotes: 0

Views: 667

Answers (1)

Petru Gardea
Petru Gardea

Reputation: 21658

Yes, it is possible.

One can define a key (either using xsd:key or xsd:unique) and then reference it using an xsd:keyref.

<?xml version="1.0" encoding="utf-8"?>
<!--XML Schema generated by QTAssistant/XML Schema Refactoring (XSR) Module (http://www.paschidev.com)-->
<xsd:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <xsd:element name="sample">
        <xsd:complexType>
            <xsd:sequence>
                <xsd:element maxOccurs="unbounded" name="SCHOOL" type="xsd:string"/>
                <xsd:element name="STUDENT" maxOccurs="unbounded">
                    <xsd:complexType>
                        <xsd:sequence>
                            <xsd:element name="SCHOOL_ID" type="xsd:string"/>
                        </xsd:sequence>
                    </xsd:complexType>
                </xsd:element>
            </xsd:sequence>
        </xsd:complexType>
        <xsd:key name="PKSchools">
            <xsd:selector xpath="SCHOOL"/>
            <xsd:field xpath="."/>
        </xsd:key>
        <xsd:keyref name="FKStudentSchool" refer="PKSchools">
            <xsd:selector xpath="STUDENT/SCHOOL_ID"/>
            <xsd:field xpath="."/>
        </xsd:keyref>
    </xsd:element>
</xsd:schema>

Schema diagram

This sample XML will fail validation:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<!-- Sample XML generated by QTAssistant (http://www.paschidev.com) -->
<sample xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <SCHOOL>001</SCHOOL>
    <STUDENT>
        <SCHOOL_ID>002</SCHOOL_ID>
    </STUDENT>
</sample>

The error message (may vary):

Error occurred while loading [], line 8 position 3 The key sequence '002' in 'PKSchools' Keyref fails to refer to some key.

Upvotes: 1

Related Questions