I have a problem, I can’t figure out the XSL code for “transforming” an xml into another xml
This is the input xml:
<?xml version="1.0" encoding="ISO-8859-1" ?>
<output>
<cars>
<car>
<id>1</id>
<brand>Audi</brand>
<type>A3</type>
<license>B-01-TST</license>
</car>
<car>
<id>2</id>
<brand>Volkwagen</brand>
<type>Golf</type>
<license>IF-02-TST</license>
</car>
</cars>
<distances>
<distance>
<id_car>1</id_car>
<date>20110901</date>
<distance>111</distance>
</distance>
<distance>
<id_car>1</id_car>
<date>20110902</date>
<distance>23</distance>
</distance>
<distance>
<id_car>1</id_car>
<date>20110903</date>
<distance>0</distance>
</distance>
<distance>
<id_car>2</id_car>
<date>20110901</date>
<distance>92</distance>
</distance>
<distance>
<id_car>2</id_car>
<date>20110902</date>
<distance>87</distance>
</distance>
<distance>
<id_car>2</id_car>
<date>20110903</date>
<distance>132</distance>
</distance>
</distances>
</output>
This is the output xml:
<?xml version="1.0" encoding="ISO-8859-1" ?>
<cars>
<car>
<id>1</id>
<brand>Audi</brand>
<type>A3</type>
<license>B-01-TST</license>
<distances>
<distance day="20110901">111</distance>
<distance day="20110902">23</distance>
<distance day="20110903">0</distance>
</distances>
</car>
<car>
<id>2</id>
<brand>Volkwagen</brand>
<type>Golf</type>
<license>IF-02-TST</license>
<distances>
<distance day="20110901">92</distance>
<distance day="20110902">87</distance>
<distance day="20110903">132</distance>
</distances>
</car>
</cars>
and the end for the element cars at the end I forgot.
Thank you.
This is actually quite easy to do using XSLT; the hardest part is the use of keys. Here’s the code you need:
The key essentially allows you to use the
keyfunction to get a list of alldistanceelements with anid_carof a given value.The first template handles the root and outputs only the
carselement.The second template handles any
carelements, outputting them exactly as they are, but adding in adistanceselement, and with the use of thekeyfunction, processes anydistanceelements with the correct ID.The last template is the ‘identity’ template that copies any elements that we haven’t already accounted for exactly as they are; this handles the
brand,type,licenseelements, and so on.