Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Value from XML and Store In Variable Using XSLT

Tags:

xml

xslt

xslt-1.0

<?xml version="1.0" encoding="UTF-8" standalone="yes" ?> 
<Result>
  <resultDetails>
    <resultDetailsData>
      <itemProperties>
        <ID>1</ID>
        <type>LEVEL</type> 
        <value xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xs="http://www.w3.org/2001/XMLSchema" xsi:type="xs:int">5</value> 
      </itemProperties>
    </resultDetailsData>
  </resultDetails>
</Result>

I have the xml described above. I want to get the value of value tag (in this case, '5') using the value of the type tag, (i.e., LEVEL in this case) and store it in a variable using XSLT, so that i can use the variable later.

How do I do it?

like image 433
Harshdip Singh Avatar asked Mar 25 '13 08:03

Harshdip Singh


People also ask

How do you store values in XSLT?

XSLT provides the <xsl:variable> element, which allows you to store a value and associate it with a name. This element creates a new variable named x , whose value is an empty string. (Please hold your applause until the end of the section.) In this case, we've set the value of the variable to be the string “blue”.

How do I assign a value to a variable in XSLT?

XSLT <xsl:variable>The <xsl:variable> element is used to declare a local or global variable. Note: The variable is global if it's declared as a top-level element, and local if it's declared within a template. Note: Once you have set a variable's value, you cannot change or modify that value!

Can we reassign a value to variable in XSLT?

Variables in XSLT are not really variables, as their values cannot be changed. They resemble constants from conventional programming languages. The only way in which a variable can be changed is by declaring it inside a for-each loop, in which case its value will be updated for every iteration.


2 Answers

You could do it this way:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
version="1.0">

<xsl:template match="/">
    <xsl:variable name="myVar" select="Result/resultDetails/resultDetailsData/itemProperties/value"/>
<varoutput>
    <xsl:value-of select="$myVar"/>
</varoutput>
</xsl:template> 

</xsl:stylesheet>

Applied to your input XML you get this output:

<?xml version="1.0" encoding="UTF-8"?>
<varoutput>5</varoutput>
like image 164
Peter Avatar answered Sep 20 '22 17:09

Peter


If you want to use the read variable to set an attribute (i.e. color of a row) you need to use {$variable} as below

<xsl:variable name="rColor" select="rowColor"/>

then

<fo:table-row background-color="{$rColor}">
like image 36
user2615206 Avatar answered Sep 16 '22 17:09

user2615206