I have a project where the main file we are dealing with is an old XML file where the creator made a very unstructured DTD (All elements are optional, and can occur 0 or more times. Even better the application which reads the file actually expects many of the values as required). I have created an XSD based upon known application requirements, and moved the unordered element lists into sequences in the XSD.
Is there an simple transformation process (e.g. XSLT) which can take an old XML file, and order its elements in a specified way so that we can use the new XSD to validate it?
Example:
<Top>
<A/>
<D/>
<B/>
<C/>
<A/>
</TOP>
INTO
<Top>
<A/>
<A/>
<B/>
<C/>
<D/>
</TOP>
Also children also might have elements which need to also be sorted into the new sequence expected ordering. Thanks!
I'm assuming you don't want to alphabetize your elements, but rather put them in the order you specify. Try this--you'll need an XSLT processor (e.g. Saxon), and save this file as a *.xsl.
BIG caveat though: XML is case-sensitive, so your
<Top>
and</TOP>
tags don't match, so you don't have well-formed XML, so the XSLT processor will throw an error and quit.<xsl:copy-of>
copies the matched element and ALL its children (incl. attributes). To re-order deeper levels, you can replacexsl:copy-of
withxsl:copy
and then call a similar template from there to output the next level in order.Instead of specifying all the elements to order within a template, you may use in a more declarative way a "lookup list" embedded in the stylesheet:
This sample:
will return: