can we use dynamic variable name in the select statement in xslt? - xslt

I wanted to use a dynamic variable name in the select statement in xslt.
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:template match="/">
<xsl:variable name="input" select="input/message" />
<xsl:variable name="Name" select="'MyName'" />
<xsl:variable name="Address" select="MyAddress" />
<xsl:variable name="output" select="concat('$','$input')" /> <!-- This is not working -->
<output>
<xsl:value-of select="$output" />
</output>
</xsl:template>
The possible values for the variable "input" is 'Name' or 'Address'.
The select statement of the output variable should have a dynamic variable name based on the value of input variable. I don't want to use xsl:choose. I wanted to select the value dynamically.
Please provide me a solution.
Thanks,
dhinu

XSLT 1.0 and XSLT 2.0 don't have dynamic evaluation.
Solution for your problem:
This transformation:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:my="my:my">
<xsl:output method="text"/>
<my:values>
<name>MyName</name>
<address>MyAdress</address>
</my:values>
<xsl:template match="/">
<xsl:variable name="vSelector"
select="input/message"/>
<xsl:value-of select=
"document('')/*/my:values/*[name()=$vSelector]"/>
</xsl:template>
</xsl:stylesheet>
when applied on the following XML document:
<input>
<message>address</message>
</input>
produces the wanted, correct result:
MyAdress
when the same transformation is applied on this XML document:
<input>
<message>name</message>
</input>
again the wanted, correct result is produced:
MyName
Finally: If you do not wish to use the document() function, but would go for using the xxx:node-set() extension function, then this solution (looking very similar) is what you want, where you may consult your XSLTprocessor documentation for the exact namespace of the extension:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:ext="http://exslt.org/common" >
<xsl:output method="text"/>
<xsl:variable name="vValues">
<name>MyName</name>
<address>MyAdress</address>
</xsl:variable>
<xsl:template match="/">
<xsl:variable name="vSelector"
select="input/message"/>
<xsl:value-of select=
"ext:node-set($vValues)/*[name()=$vSelector]"/>
</xsl:template>
</xsl:stylesheet>

Beside #Dimitre's good answer, for this particular case (output string value) you could also use:
<xsl:variable name="output"
select="concat(substring($Name, 1 div ($input = 'Name')),
substring($Address, 1 div ($input = 'Address')))"/>

Related

XSLT correct approach in writing XPath expression used in multiple condition checking and displaying value

Considering this XML,
XML:
<?xml version="1.0" encoding="UTF-8"?>
<items>
<book>
<title>doublebell</title>
<count>available</count>
</book>
<phone>
<brand>nokia</brand>
<model></model>
</phone>
</items>
Mapping Criteria while writing XSLT:
show the newbook/newtitle only if a value is present in input.
show the newbook/newcount only if a value is present in input.
show the newphone/newbrand only if a value is present in input.
show the newphone/newmodel only if a value is present in input.
XSLT:
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8"
indent="yes" />
<xsl:variable name="book" select="items/book" />
<xsl:variable name="phone" select="items/phone" />
<xsl:template match="/">
<items>
<newbook>
<xsl:if test="$book/title!=''">
<newtitle>
<xsl:value-of select="$book/title" />
</newtitle>
</xsl:if>
<xsl:if test="$book/count!=''">
<newcount>
<xsl:value-of select="$book/count" />
</newcount>
</xsl:if>
</newbook>
<xsl:if test="$phone/brand!='' or $phone/model!=''"> <!-- not sure if this condition is required for the above mapping criteria -->
<newphone>
<xsl:if test="$phone/brand!=''">
<newbrand>
<xsl:value-of select="$phone/brand" />
</newbrand>
</xsl:if>
<xsl:if test="$phone/model!=''">
<newmodel>
<xsl:value-of select="$phone/model" />
</newmodel>
</xsl:if>
</newphone>
</xsl:if>
</items>
</xsl:template>
</xsl:stylesheet>
This is my concern:- In my actual XSLT, I have almost 70 conditions like
this, and everytime the XPath search is made twice [or thrice.. ] for
each condition [ for eg: <xsl:if test="$phone/brand!=''"> and <xsl:value-of select="$phone/brand" /> and outer if condition].
Is this much performance overhead? I don't feel it when I ran my application.
I like to hear from experienced people if this is correct way of writing the XSLT. Do I need to save the path in a variable and reuse it as done for $book
and $phone ? In such a case there will be 70+variables just to hold this.
You can approach this quite differently using templates. If you define a template that matches any element whose content is empty and does nothing:
<xsl:template match="*[. = '']" />
or possibly use normalize-space() if you want to consider elements to be empty if they contain only whitespace
<xsl:template match="*[not(normalize-space())]" />
Now with this in place add templates for the elements you are interested in
<xsl:template match="book">
<newbook><xsl:apply-templates /></newbook>
</xsl:template>
<xsl:template match="title">
<newtitle><xsl:apply-templates /></newtitle>
</xsl:template>
and so on. Now the book template will create a newbook element and go on to process its children. When it gets to the title it will have two different templates to choose from and will pick the "most specific" match. If the title is empty then the *[. = ''] template will win and nothing will be output, only if the title is non-empty will it create a newtitle element.
This way you let the template matcher do most of the work for you, you don't need any explicit conditional checks using xsl:if.
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8"
indent="yes" />
<xsl:template match="/">
<items><xsl:apply-templates select="items/*" /></items>
</xsl:template>
<!-- ignore empty elements -->
<xsl:template match="*[not(normalize-space())]" />
<xsl:template match="book">
<newbook><xsl:apply-templates /></newbook>
</xsl:template>
<xsl:template match="title">
<newtitle><xsl:apply-templates /></newtitle>
</xsl:template>
<!-- and so on with similar templates for the other elements -->
</xsl:stylesheet>
Building on Ian's answer, you can also make a generic template that will create the "new" elements for you without having to specify each one individually. That would look like the below:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes" />
<xsl:template match="/">
<items><xsl:apply-templates select="items/*" /></items>
</xsl:template>
<xsl:template match="*[not(normalize-space())]" />
<xsl:template match="*">
<xsl:element name="{concat('new',name())}">
<xsl:apply-templates/>
</xsl:element>
</xsl:template>
</xsl:stylesheet>
That last template just rebuilds the element by concatenating the word "new" to the front of it.

XSLT issue with reading in non-xml data

I am newbie to XSLT.
I have a requirement to read a URL and convert some of its values into XML.
I wrote a XSLT that has to take URL as the input value and create a XML file from some of the content of the URL value.
When I debugged the XSLT in XMLSPY, I noticed that the URL value is not being picked up by inputValue variable in the below code. I am not sure if my approach to input the URL and the template match are wrong.
Any help is appreciated.
Thanks in advance.
Input to XSLT:
http://host:port/abc/xyz1/6xyz6?qq=123&pp=3
Here the XSLT:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:nnc="Nnc" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:fn="http://www.w3.org/2005/xpath-functions">
<xsl:output method="xml" encoding="UTF-8" indent="yes"/>
<xsl:param name="inVal" select="xs:string(http://host:port/abc/xyz1/6xyz6?qq=123&pp=3)"/>
<xsl:template match="/">
<xsl:variable name="inputValue" select="$inVal"/>
<xsl:if test="string-length($inputValue)=0">
<xsl:message terminate="yes">
inputValue is blank
</xsl:message>
</xsl:if>
<xsl:variable name="value" as="xs:string" select="substring-after($inputValue, 'abc/' )"/>
<xsl:variable name="tokenizedValues" select="tokenize($value,'/')"/>
<xsl:for-each select="$tokenizedValues">
<xsl:if test="position() = 1">
<id>
<xsl:value-of select="."/>
</id>
</xsl:if>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
The desired XML output:
<?xml version="1.0" encoding="UTF-8"?>
<id>6xyz6</id>
<qq>123</qq>
<pp>123</pp>
Well if you want to pull in a text file then with XSLT 2.0 and later you can do that but not by simply using a URL, you need to call the unparsed-text function e.g.
<xsl:variable name="inputData" as="xs:string" select="unparsed-text('http://example.com/foo')"/>
See http://www.w3.org/TR/xslt20/#unparsed-text, depending on the encoding of your text document you need to add a second parameter when calling the function.

XPATH for first element whose name is among the names of some other elements

<choices>
<sic />
<corr />
<reg />
<orig />
</choices>
<choice>
<corr>Red</corr>
<sic>Blue</sic>
<choice>
I want to select the first element in <choice> whose name matches the name of any element in <choices>.
If name(node-set) returned a list of names instead of only the name of the first node, I could use
select="choice/*[name() = name(choices/*)][1]"
But it doesn't (at least not in 1.0), so instead I join the names together in a string and use contains():
<xsl:variable name="choices.str">
<xsl:for-each select="choices/*">
<xsl:text> </xsl:text><xsl:value-of select="concat(name(),' ')"/>
</xsl:for-each>
</xsl:variable>
<xsl:apply-templates select="choice/*[contains($choices.str,name())][1]"/>
and get what I want:
Red, the value of <corr>
Is there a more straightforward way?
I. Use this XPath 2.0 one-liner:
/*/choice/*[name() = /*/choices/*/name()][1]
When this XPath expression is evaluated against the following XML document (the provided one, but corrected to become a well-formed XML document):
<t>
<choices>
<sic />
<corr />
<reg />
<orig />
</choices>
<choice>
<corr>Red</corr>
<sic>Blue</sic>
</choice>
</t>
the correct element is selected:
<corr>Red</corr>
II. XSLT 1.0 (no keys!):
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:variable name="vNames">
<xsl:for-each select="/*/choices/*">
<xsl:value-of select="concat(' ', name(), ' ')"/>
</xsl:for-each>
</xsl:variable>
<xsl:template match="/">
<xsl:copy-of select=
"/*/choice/*
[contains($vNames, concat(' ', name(), ' '))]
[1]"/>
</xsl:template>
</xsl:stylesheet>
When this transformation is applied on the same XML document (above), again the correct element is selected (and copied to the output):
<corr>Red</corr>
III. Using keys:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:key name="kChoiceByName" match="choice/*"
use="boolean(/*/choices/*[name()=name(current())])"/>
<xsl:template match="/">
<xsl:copy-of select="/*/choice/*[key('kChoiceByName', true())][1]"/>
</xsl:template>
</xsl:stylesheet>
When this transformation is applied against the same XML document (above), the same correct result is produced:
<corr>Red</corr>
It is recommended to the reader to try to understand how this all "works" :)
You can use the key() function like this...
When this input document...
<t>
<choices>
<sic />
<corr />
<reg />
<orig />
</choices>
<choice>
<corr>Red</corr>
<sic>Blue</sic>
</choice>
</t>
...is supplied as input to this XSLT 1.0 style-sheet...
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text"/>
<xsl:key name="kChoices" match="choices/*" use="name()" />
<xsl:template match="/">
<xsl:variable name="first-choice" select="(*/choice/*[key('kChoices',name())])[1]" />
<xsl:value-of select="$first-choice" />
<xsl:text>, the value of <</xsl:text>
<xsl:value-of select="name( $first-choice)" />
<xsl:text>></xsl:text>
</xsl:template>
</xsl:stylesheet>
...this output text is produced...
Red, the value of <corr>
XSLT 2.0 Aside
In XSLT 2.0, you would be able to use the following alternatives for the computation of the $first-choice variable...
Option 1:
(*/choice/*[for $c in . return ../../choices/*[name()=name($c)]])[1]
Option 2:
(*/choice/*[some $c in ../../choices/* satisfies name($c)=name()])[1]

Generate XSLT to map source value structures to destination field depending on source content

I have a source list of xml in this format:
<metadata>
<metadatum>
<description>OnEnter</description>
<value>Hello World</id>
</metadatum>
<metadatum>
<description>OnLeave</description>
<value>Goodbye World</id>
</metadatum>
</metadata>
and a target structure like this:
<friendlyText>
<onEnter>[Content Here]</onEnter>
<onLeave>[Content Here]</onLeave>
</friendlyText>
Is it possible to create an XSLT that will map the 'value' field in the metadata hierarchy to the proper target node depending on the source 'description'?
I'm trying to get this done with Altova MapForce; it feels like there should be an interface to allow this, I'm just not finding it.
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >
<xsl:output method="xml" indent="yes"/>
<xsl:template match="metadata">
<friendlyText>
<xsl:apply-templates select="metadatum"/>
</friendlyText>
</xsl:template>
<xsl:template match="metadatum">
<xsl:element name="{description}">
<xsl:value-of select="value"/>
</xsl:element>
</xsl:template>
</xsl:stylesheet>
Output:
<?xml version="1.0" encoding="utf-8"?>
<friendlyText>
<OnEnter>Hello World</OnEnter>
<OnLeave>Goodbye World</OnLeave>
</friendlyText>
This transformation is a general solution that can work with any "target structure" that is in a separate XML document:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:my="my:my" exclude-result-prefixes="my">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:variable name="vUpper" select=
"'ABCDEFGHIJKLMNOPQRSTUVWXYZ'"/>
<xsl:variable name="vLower" select=
"'abcdefghijklmnopqrstuvwxyz'"/>
<my:target>
<friendlyText>
<onEnter>[Content Here]</onEnter>
<onLeave>[Content Here]</onLeave>
</friendlyText>
</my:target>
<xsl:variable name="vTarget" select="document('')/*/my:target/*"/>
<xsl:variable name="vMeta" select="/*/metadatum"/>
<xsl:template match="node()|#*">
<xsl:copy>
<xsl:apply-templates select="node()|#*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="/">
<xsl:apply-templates select="$vTarget"/>
</xsl:template>
<xsl:template match="friendlyText/*/text()">
<xsl:value-of select=
"$vMeta[translate(description, $vLower, $vUpper)
=
translate(name(current()/..), $vLower, $vUpper)
]/value"/>
</xsl:template>
</xsl:stylesheet>
when applied on the provided XML document (corrected to be made well-formed):
<metadata>
<metadatum>
<description>OnEnter</description>
<value>Hello World</value>
</metadatum>
<metadatum>
<description>OnLeave</description>
<value>Goodbye World</value>
</metadatum>
</metadata>
produces the wanted, correct result:
<friendlyText xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:my="my:my">
<onEnter>Hello World</onEnter>
<onLeave>Goodbye World</onLeave>
</friendlyText>
Do note: Only for convenience, the "target structure" is inline here. In a real world case it would be better to keep the "target structure" in a separate file and to load it using the document() function. Only the line:
<xsl:variable name="vTarget" select="document('')/*/my:target/*"/>
will need to be changed to:
<xsl:variable name="vTarget" select="document('someFileUrl')/*"/>

XSL: How to concatenate nodes with conditions?

I have the following code (eg):
<response>
<parameter>
<cottage>
<cot>
<res>
<hab desc="Lakeside">
<reg cod="OB" prr="600.84>
<lwz>TR#2#AB#200.26#0#QB#OK#20120829#20120830#EU#3-0#</lwz>
<lwz>TR#2#AB#200.26#0#QB#OK#20120830#20120831#EU#3-0#</lwz>
<lwz>TR#2#AB#200.26#0#QB#OK#20120831#20120901#EU#3-0#</lwz>
I need to create a concatenated string that includes the whole of the first 'lwz' line and then the price (200.26, but it can be different in each line) for each corresponding line.
So the output, separating each line with | would be:
TR#2#AB#200.26#0#QB#OK#20120829#20120830#EU#3-0#|200.26|200.26
Thanks
This XSLT 1.0 transformation:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text"/>
<xsl:strip-space elements="*"/>
<xsl:template match="lwz[1]">
<xsl:value-of select="."/>
</xsl:template>
<xsl:template match="lwz[position() >1]">
<xsl:value-of select=
"concat('
',
substring-before(substring-after(substring-after(substring-after(.,'#'),'#'),'#'),'#')
)
"/>
</xsl:template>
<xsl:template match="text()"/>
</xsl:stylesheet>
when applied on the provided text (converted to a well-formed XML document !!!):
<response>
<parameter>
<cottage>
<cot>
<res>
<hab desc="Lakeside">
<reg cod="OB" prr="600.84">
<lwz>TR#2#AB#200.26#0#QB#OK#20120829#20120830#EU#3-0#</lwz>
<lwz>TR#2#AB#200.26#0#QB#OK#20120830#20120831#EU#3-0#</lwz>
<lwz>TR#2#AB#200.26#0#QB#OK#20120831#20120901#EU#3-0#</lwz>
</reg>
</hab>
</res>
</cot>
</cottage>
</parameter>
</response>
produces the wanted, correct result:
TR#2#AB#200.26#0#QB#OK#20120829#20120830#EU#3-0#
200.26
200.26
II XSLT 2.0 solution:
This transformation:
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text"/>
<xsl:strip-space elements="*"/>
<xsl:template match="lwz[1]">
<xsl:value-of select="."/>
</xsl:template>
<xsl:template match="lwz[position() >1]">
<xsl:value-of select=
"concat('
', tokenize(.,'#')[4])"/>
</xsl:template>
<xsl:template match="text()"/>
</xsl:stylesheet>
when applied on the above XML document, again produces the wanted, correct result. Note the use of the standard XPath 2.0 function tokenize():
TR#2#AB#200.26#0#QB#OK#20120829#20120830#EU#3-0#
200.26
200.26
You can use the XPath substring function to select substrings from your lwz node data. You don't really give much more detail about your problem, if you want a more detailed answer, perhaps provide the full XML document and your best-guess XSLT