title: Using a schema to reorder the elements of an XML document in conformance with the schema
body: <p>Say I have an XML document (represented as text, a W3C DOM, whatever), and also an XML Schema. The XML document has all the right elements as defined by the schema, but in the wrong order.</p>
  
  <p>How do I use the schema to "re-order" the elements in the document to conform to the ordering defined by the schema?</p>
  
  <p>I know that this should be possible, probably using <a href="https://xsom.dev.java.net" rel="nofollow noreferrer">XSOM</a>, since the JAXB XJC code generator annotates its generated classes with the correct serialization order of the elements.</p>
  
  <p>However, I'm not familiar with the XSOM API, and it's pretty dense, so I'm hoping one of you lot has some experience with it, and can point me in the right direction.  Something like "what child elements are permitted inside this parent element, and in what order?"</p>
  
  <hr>
  
  <p>Let me give an example.</p>
  
  <p>I have an XML document like this:</p>
  
  <pre><code>&lt;A&gt;
     &lt;Y/&gt;
     &lt;X/&gt;
  &lt;/A&gt;
  </code></pre>
  
  <p>I have an XML Schema which says that the contents of <code>&lt;A&gt;</code> must be an <code>&lt;X&gt;</code> followed by a <code>&lt;Y&gt;</code>. Now clearly, if I try to validate the document against the schema, it fails, since the <code>&lt;X&gt;</code> and <code>&lt;Y&gt;</code> are in the wrong order. But I know my document is "wrong" in advance, so I'm not using the schema to validate just yet. However, I <em>do</em> know that my document has all of the correct elements as defined by the schema, just in the wrong order.</p>
  
  <p>What I want to do is to programmatically examine the Schema (probably using XSOM - which is an object model for XML Schema), and ask it what the contents of <code>&lt;A&gt;</code> should be. The API will expose the information that "you need an <code>&lt;X&gt;</code> followed by a <code>&lt;Y&gt;</code>". </p>
  
  <p>So I take my XML document (using a DOM API) and re-arrange  and  accordingly, so that now the document will validate against the schema.</p>
  
  <p>It's important to understand what XSOM is here - it's a java API which represents the information contained in an XML Schema, <em>not</em> the information contained in my instance document.</p>
  
  <p>What I don't want to do is generate code from the schema, since the schema is unknown at build time. Furthermore, XSLT is no use, since the correct ordering of the elements is determined solely by the data dictionary contained in the schema.</p>
  
  <p>Hopefully that's now explicit enough.</p>