Reputation: 1310
I've been using XSLT to clean up some legacy XML code into a cleaner format. Here's a case I haven't figured out a proper solution to. The starting XML looks like this:
<MyPoints>
<X_Values>
<X>11</X>
<X>12</X>
<X>13</X>
</X_Values>
<Y_Values>
<Y>21</Y>
<Y>22</Y>
<Y>23</Y>
</Y_Values>
</MyPoints>
Here's what I would like to get:
<MyPoints>
<Values>
<Value X="11" Y="21" />
<Value X="12" Y="22" />
<Value X="13" Y="23" />
</Values>
</MyPoints>
X_Values and Y_Values are guaranteed to have the same number of elements. I want to do this for 3D points as well, but that should be a trivial extension of the solution.
XSLT 1.0 would be nice if possible.
Upvotes: 0
Views: 101
Reputation: 34636
Using position()
should do the trick. The relevant part:
<xsl:for-each select="/MyPoints/X_Values/X">
<xsl:variable name="i"><xsl:value-of select="position()" /></xsl:variable>
<Value X="{.}" Y="{/MyPoints/Y_Values/Y[position()=$i]}" />
</xsl:for-each>
A full stylesheet:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet
version="1.0"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:fn="http://www.w3.org/2005/xpath-functions"
>
<xsl:output
method="xml"
version="1.0"
indent="yes"
doctype-public="-//W3C//DTD XHTML 1.1//EN"
doctype-system="http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"
/>
<xsl:template match="/">
<MyPoints><Values>
<xsl:for-each select="/MyPoints/X_Values/X">
<xsl:variable name="i"><xsl:value-of select="position()" /></xsl:variable>
<Value X="{.}" Y="{/MyPoints/Y_Values/Y[position()=$i]}" />
</xsl:for-each>
</Values></MyPoints>
</xsl:template>
</xsl:stylesheet>
Upvotes: 1