How to use a variable in Xpath select expression

M

Murtaza Tinwala

Hi mates,

I am having the following problem in XSLT. I have the following three
variables which I receive from an XML document.

$xmlfile = "doc.xml"
$repeatpath = "/root/person"
$path = "name"

Suppose, the file doc.xml containls the following XML document:

<?xml version="1.0" encoding="UTF-8"?>
<root>
<person>
<name>Murtaza</name>
<surname>tinwala</surname>
</person>
<person>
<name>Rishit</name>
<surname>udani</surname>
</person>
<person>
<name>Nilesh</name>
<surname>ruparelia</surname>
</person>
</root>

From $xmlfile, I am loading the external XML document ( <xsl:variable
name="xmldatabase" select="document($xmlfile)"/>). The variable
$repeatpath contains the Xpath expression on which I have to run a
XSLT for-each loop. The variable $path contains the node, which I
have to output somewhere.

Now, the problem is I want to express Xpath expression in string
format like the following way:

<xsl:for-each select="$xmldatabase/$repeatpath">

But, that is not possible, because we cannot use variables for select
expressions. How should I solve this problem?

Murtaza Tinwala.
 
D

David Carlisle

<xsl:for-each select="$xmldatabase/$repeatpath">

But, that is not possible, because we cannot use variables for select
expressions. How should I solve this problem?


That is not your problem. You can use variables in select expressions,
the above is perfectly legal syntax so long as the variables have the
correct types, which is node set in this case.

Your $xmldatabase variable is node set valued but $repeatpath is probably
string valued (you don't show how it is set) so the problem is not that
you have variables but that your expression is equivalent to

<xsl:for-each select="$xmldatabase/'/root/person'">

and you can't have a string after /.



Some systems have an evaluate() extension (saxon for example has such a
thing) which can evaluate a string as an Xpath, otherwise, if this is an
extrnal global parameter which it appears to be your API may allow you
to pass in a node set directly rather than a string.

David
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top