title: XML Schema key/keyref - how to use them?
body: <p>Long story short : i would like to know how to use the key/keyref from XSD to let elements have references to each other. it has to have a form of an example, using a simple xsd and an XML.</p>
  
  <p>Long story : I am familiar with usage of ID/IDREF. I use those to connect elements for JAXB. I have been told repeatedly that the key/keyref construct in XSD offers enhanced flexibility for inter-element referencing. I have consulted the <a href="http://oreilly.com/catalog/9780596002527" rel="noreferrer">OReilly XML Schema book</a>, that seems to teach everything about correct definition of key/keyref and how it is similar to the ID/IDREF (but better) and doesn't give a simple example of its use. It doesn't seem to be similar, because you define the ID as an attribute in one element and the IDREF in another element and voila. But key/keyref have to be defined in a common ancestor of the referencing and the referenced element (AFAIK)...</p>
  
  <p>I use the XSD files to generate JAXB-bound Java classes with XJC</p>
  
  <p>I have searched for how-tos, tutorials and examples, but google gives me scraps. same for searches on SO (also with google and inclusive search with '+' ).</p>
  
  <p>In order to make everyone's lives easier i have prepared an XSD with already defined key/keyref pair as i have understood it. </p>
  
  <pre><code>&lt;xs:schema elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema"&gt;
  &lt;xs:element name="root"&gt;
      &lt;xs:complexType&gt;
          &lt;xs:sequence&gt;
              &lt;xs:element name="referenced"&gt;
                  &lt;xs:complexType&gt;
                      &lt;xs:attribute name="id" type="xs:string" /&gt;
                  &lt;/xs:complexType&gt;
              &lt;/xs:element&gt;
              &lt;xs:element name="owner"&gt;
                  &lt;xs:complexType&gt;
                      &lt;xs:attribute name="id" type="xs:string" /&gt;
                  &lt;/xs:complexType&gt;
              &lt;/xs:element&gt;
          &lt;/xs:sequence&gt;
      &lt;/xs:complexType&gt;
      &lt;xs:key name="aKey"&gt;
          &lt;xs:selector xpath="owner" /&gt;
          &lt;xs:field xpath="@id" /&gt;
      &lt;/xs:key&gt;
      &lt;xs:keyref name="aKeyRef" refer="aKey"&gt;
          &lt;xs:selector xpath="referenced" /&gt;
          &lt;xs:field xpath="@id" /&gt;
      &lt;/xs:keyref&gt;
  &lt;/xs:element&gt;
  </code></pre>
  
  <p></p>
  
  <p>How would a piece of XML look like, with an 'owner'-element referencing a 'referenced'-element?</p>
  
  <p><b>EDIT : </b> applied the change proposed by Tom W, changing the xpath attribute of the key element to "owner". JAXB (XJC) still doesnt care though.</p>
  
  <p>Thank you</p>