XML Schema key/keyref - how to use them? XML Schema key/keyref - how to use them? xml xml

XML Schema key/keyref - how to use them?


There is no special syntax in the instance document. It is simply required that the keyref node matches an extant key node. Validation will tell you whether or not the key constraint is satisfied.

RE your code:

I've only just started dabbling with keys myself, but I think I've spotted an error in yours - aKey should look like:

<xs:key name="aKey">    <xs:selector xpath="owner" />    <xs:field xpath="@id" /></xs:key>

Furthermore - this is a gotcha - key constraints don't recognise the default namespace. You must always prefix every part of the selector xpath with the namespace prefix of the element you're looking up. If you don't have a namespace prefix - tough, you'll need to add one. This is a limitation of the standard.


The JAXB spec does not explicitly cover key/keyref. However JAXB implemenations such as EclipseLink MOXy (I'm the tech lead) have extensions for this. Our upcoming 2.2 release provides a means to specify this kind of relationship via annotations (I'll put together an example). Below is a link to how it can be done using the current release.

For more information see:

UPDATE

I was hoping to get an example included with the answer, but I am running out of time before I leave on vacation. Below is an example from our design documents that demonstrates the concept:


I found this thread searching for the same thing the OP was searching for - a simple usage example of the <xs:key> element. All the JAXB stuff was greek to me, and a distraction. For others finding this thread later, here's a simple example posted on MSDN a couple years after the OP asked the question here on SO:

https://msdn.microsoft.com/en-us/library/ms256101%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396

In case the MSDN link changes, the breadcrumb path was:

https://msdn.microsoft.com/library then click "Switch to Library TOC view", and drill down through:

MSDN Library > .NET development > .NET Framework 4.6 and 4.5 > Development Guide > Data and Modeling > XML Standards Reference > XML Schemas (XSD) Reference > XML Schema Elements > <xsd:key> Element