This section describes the 'keyref' identity-constraint, where a combination of certain sub elements or attributes is defined as a key reference identity, which must have values that reference to an existing key identity.
What Is "keyref" Identity-Constraint?
A "keyref" Identity-Constraint is a constraint on an XML element, where
a combination of certain sub elements or attributes is defined as a key reference identity,
which must have values that reference to an existing key identity.
"keyref" identity-constraint in XML document is very similar to the concept of
FOREIGN KEY constraint on multiple columns in a database table.
Here is the syntax on how a "keyref" identity-constraint should be defined
in XSD schema:
The "keyref" declaration must be placed inside the "element" statement
which declares the parent element where the constraint will be applied.
"keyref[@name]" attribute is required to provide a name for this key reference identity constraint.
"keyref[@refer]" attribute is required to provide the name of a key identity constraint.
"selector" is required to specify a relative XPath to match a sequence of sub elements
from which identity values will be constructed and validated.
At least 1 "field" is required.
Each "field" specifies a relative XPath pointing to an attribute or a simple element content,
which will be used as part of the identity construction.
For example, I have the following XML document, keyref_identity.xml:
<?xml version="1.0" encoding="utf-8"?>
<!-- keyref_identity.xml
- Copyright (c) 2014, HerongYang.com, All Rights Reserved.
-->
<survey>
<questions>
<question code="Java">What is Java?</question>
<question code="John">Who is John?</question>
<question code="Jim1">Where is Jim?</question>
<question code="Jim2">What is Jim doing?</question>
</questions>
<answers>
<answer qcode="Java">Java is an island of Indonesia.</answer>
<answer qcode="Java">Java is programming language.</answer>
<answer qcode="John">John is a character in Atlas Shrugged.</answer>
<answer qcode="Jojo">Jojo is a singer-songwriter.</answer>
<answer qcode="Jim1">Jim is in Java island.</answer>
<answer qcode="Jim2">Jim is having a coffee.</answer>
<answer>These are good questions.</answer>
</answers>
</survey>
For this XML document, I want to have an XSD schema
that has two identity-constraints to ensure values in "question[@code]" attributes can be used as a key identity.
And values in "answer[@qcode]" attributes are referring to an existing value in "question[@code]" attribute.
See next section for the XSD schema example and validation result.