Reputation: 15
Folks: Kindly excuse on this newbie question, but please do help me out -
I'm using XSL to manipulate some values within an XML which looks as below -
<userFields>
<userField>
<FieldName>TEST1</FieldName>
<FieldVal>123</FieldVal>
<Fieldtype>char</Fieldtype>
</userField>
<userField>
<FieldName>TEST2</FieldName>
<FieldVal>999</FieldVal>
<Fieldtype>char</Fieldtype>
</userField>
<userField>
<FieldName>TEST3</FieldName>
<FieldVal>756</FieldVal>
<Fieldtype>char</Fieldtype>
</userField>
<userField>
<FieldName>TEST4</FieldName>
<FieldVal>1234</FieldVal>
<Fieldtype>char</Fieldtype>
</userField>
...
</userFields>
I need to get the FieldVal for a specific "FieldName", say I need the FieldVal for FieldName "TEST2" (in this case which is 999), how do I accomplish this please? Intent is to store the value in a variable and add it as a seperate user field within the XML, so the result looks like this -
<userFields>
<userField>
<FieldName>TEST1</FieldName>
<FieldVal>123</FieldVal>
<Fieldtype>char</Fieldtype>
</userField>
<userField>
<FieldName>TEST2</FieldName>
<FieldVal>999</FieldVal>
<Fieldtype>char</Fieldtype>
</userField>
<userField>
<FieldName>TEST3</FieldName>
<FieldVal>756</FieldVal>
<Fieldtype>char</Fieldtype>
</userField>
<userField>
<FieldName>TEST4</FieldName>
<FieldVal>1234</FieldVal>
<Fieldtype>char</Fieldtype>
</userField>
...
</userFields>
<variableX>999</variableX>
I would like to store the Fieldval of TEST2 in a variableX within the XML. this is so cause I can pass this variable as an argument for a subsequent db fetch. Thank you.
Upvotes: 0
Views: 250
Reputation: 70618
The expression you are looking for is this..
<xsl:variable name="field" select="//userField[FieldName='TEST2']/FieldVal" />
Alternatively, define a key to lookup the elements..
<xsl:key name="userFields" match="userField" use="FieldName" />
Then you can do the look-up like so...
<xsl:variable name="field" select="key('userFields', 'TEST2')/FieldVal" />
Try this XSLT
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:key name="userFields" match="userField" use="FieldName" />
<xsl:param name="fieldName" select="'TEST4'" />
<xsl:variable name="field" select="key('userFields', $fieldName)/FieldVal" />
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="userFields">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
<variableX>
<xsl:value-of select="$field" />
</variableX>
</xsl:template>
</xsl:stylesheet>
Note I have made the "TEST2" a parameter so it could be passed in by the main application.
Also note the use of the Identity Template to copy existing values.
Upvotes: 1