I'm having trouble with an XSLT transformation of XML fragments. The source XML looks like so:
<XXX>
<Name>Sample</Name>
<MMM>
<AAA ID="A"/>
<MMM>
<BBB ID="B"/>
<MMM>
<AA ID="C"/>
<BB ID="D"/>
</MMM>
</MMM>
</MMM>
</XXX>
But it needs to be transformed into:
<XXX>
<Name>Sample</Name>
<MMM>
<MMM>
<MMM>
<AAA ID="A"/>
<BBB ID="B"/>
</MMM>
<AA ID="C"/>
</MMM>
<BB ID="D"/>
</MMM>
</XXX>
The rule is simple, the MMM element can only have two child element nodes. If only one of those nodes happen to be another MMM, it needs to occupy the first position.
It is easy using code, but these XML fragments are values to XML columns in an SQL database, and I want to use SQL along with XSLT to update those values.
Any pointer or suggestions?
One way to solve this is to first extract the
MMM
tree on the one hand and the other nodes on the other hand into separate structures and then to merge them again.This was really a nice challenge! Made me stay up until 4:00 AM.
The following XSLT (almost! see below) does the job:
Notes:
MMM
nodes with two children are also handled. The rule of placing the other nodes is such that the positions are filled from the bottom to the top.This is the output:
If this is a problem let me know.