Child node attribute in XSLT - xslt

Is it possible to access child node attributes in xsl:if
I have to convert that Xml to text file
<Report>
<Total>
<RecordValues>
<Record>
<FieldValue fieldName="index" fieldValue="1" />
<FieldValue fieldName="dtrk_sysid" fieldValue="0"/>
<FieldValue fieldName="version" fieldValue="100" />
<FieldValue fieldName="user" fieldValue="tester" />
<FieldValue fieldName="date_modified" fieldValue="2010-10-18 12:18:12" />
<FieldValue fieldName="object_name" fieldValue="Menu" />
<FieldValue fieldName="permission" fieldValue="Permission X" />
</Record>
<Record>
<FieldValue fieldName="index" fieldValue="2" />
<FieldValue fieldName="dtrk_sysid" fieldValue="55555"/>
<FieldValue fieldName="version" fieldValue="100" />
<FieldValue fieldName="user" fieldValue="user1" />
<FieldValue fieldName="date_modified" fieldValue="2010-12-15 12:18:12" />
<FieldValue fieldName="object_name" fieldValue="Control" />
<FieldValue fieldName="permission" fieldValue="Permission E" />
</Record>
<Record>
<FieldValue fieldName="index" fieldValue="3" />
<FieldValue fieldName="dtrk_sysid" fieldValue="55555"/>
<FieldValue fieldName="version" fieldValue="15" />
<FieldValue fieldName="user" fieldValue="user2" />
<FieldValue fieldName="date_modified" fieldValue="2010-10-02 12:18:12" />
<FieldValue fieldName="object_name" fieldValue="Run" />
<FieldValue fieldName="permission" fieldValue="Permission R" />
</Record>
</RecordValues>
</Total>
I already know how to do that, but the file must have header record which is should appear only once as the first record of the file. It must contains some default values and some values from FieldValue node.
Here is the example of header record:
HDRTT55555EE000KK20101018UU
1 100 101810
tester Menu Permission X
2 100 121510
user1 Control Permission E
3 15 100210
user2 Run Permission R
Here is what I've done so far:
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" indent="yes" encoding="UTF-8" omit-xml- declaration="yes"/>
<xsl:template match="/">
<xsl:apply-templates select="/Report/Total/RecordValues"/>
<xsl:apply-templates select="/Report/Total/RecordValues/Record/FieldValue"/>
</xsl:template>
<xsl:template match="RecordValues">
<xsl:text>HDR</xsl:text>
<xsl:text>TT</xsl:text>
<xsl:variable name="fvsys" select="Record/FieldValue[#fieldName = 'dtrk_sysid']"/>
<xsl:choose>
<xsl:when test="$fvsys/#fieldValue != '0'">
<xsl:value-of select="$fvsys/#fieldValue"/>
</xsl:when>
<xsl:otherwise>
<xsl:text>12343</xsl:text>
</xsl:otherwise>
</xsl:choose>
<xsl:text>EE</xsl:text>
<xsl:text>000</xsl:text>
<xsl:text>KK</xsl:text>
<xsl:if test="Record/FieldValue[#fieldName='date_modified']">
<xsl:call-template name="ppad">
<xsl:with-param name="str" select="concat(substring(translate(Record/FieldValue[#fieldName = 'date_modified']/#fieldValue,'-',''),5,4), substring(Record/FieldValue[#fieldName = 'date_modified']/#fieldValue,3,2))"/>
<xsl:with-param name="len" select="6"/>
</xsl:call-template>
</xsl:if>
<xsl:text>UU</xsl:text>
<xsl:text>
</xsl:text>
</xsl:template>
<xsl:template match="FieldValue">
</xsl:template>
<xsl:template name="ppad">
<xsl:param name="str"/>
<xsl:param name="chr" select="' '"/>
<xsl:param name="len" select="0"/>
<xsl:choose>
<xsl:when test="string-length($str) < $len">
<xsl:call-template name="ppad">
<xsl:with-param name="str" select="concat($str, $chr)"/>
<xsl:with-param name="len" select="$len"/>
<xsl:with-param name="chr" select="$chr"/>
</xsl:call-template>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="$str"/>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
</xsl:stylesheet>
Thanks for your help.

The main problem with the following if statement:
<xsl:if test="Record/FieldValue/#fieldName='dtrk_sysid' and Record/FieldValue/#fieldValue!='0'">
<xsl:value-of select="Record/FieldValue/#fieldValue"/>
</xsl:if>
is that the #fieldValue you're trying to compare after the and is supposed to be the #fieldValue of the <FieldValue> whose #fieldName is 'dtrk_sysid', but there is nothing that limits the second comparison to that particular <FieldValue>. The <xsl:if test=...> does not set a context. <xsl:value-of> will then select the first #fieldValue attribute of all Record/FieldValue nodes under the context node, which by luck happens to be the right one, in your sample input XML (but maybe not always?).
To fix that, you can capture the context (the <FieldValue> whose #fieldName is 'dtrk_sysid') in a variable:
<xsl:variable name="fvsys" select="(Record/FieldValue[#fieldName = 'dtrk_sysid'])[1]"/>
Then you can replace your first two if statements with:
<xsl:choose>
<xsl:when test="$fvsys/#fieldValue != '0'">
<xsl:value-of select="$fvsys/#fieldValue"/>
</xsl:when>
<xsl:otherwise>
<xsl:text>12343</xsl:text>
</xsl:otherwise>
</xsl:choose>
(The above has been modified to fit the behavior described in comments.)
You can replace your third if statement with:
<xsl:value-of select="(Record/FieldValue[#fieldName = 'date_modified'])[1]/#fieldValue"/>
This will not output anything if no such FieldValue exists.
If after this you're still not getting the desired output, tell us what output you are getting, and how it differs from the desired output.

Related

Generic XSLT to do XML to CSV - almost there, but stuck

I have gathered bits and pieces of this XSLT from these forums. I'm trying to put them altogether to create a single, generic XSLT that can be used to convert XML to CSV by specifying the path to the nodes that should be included in the CSV file.
I have three things that I still can't figure out after about 10 hours of messing with it.
I want to iterate over each column named in csv:columns. During each iteration, I need to extract and store the text() of the column. I think this is the way to iterate, but want to make sure:
<xsl:for-each select="document('')/*/csv:columns/*">
Once I have the text() from the column, I need to put that into the columnname variable in such a way that it works when it is used with getNodeValue.
I was unable to set columnname using variable. If I didn't hard-code the value (surrounded by apostrophes), I could not get it to work. This is why I have the following line in the code:
<xsl:variable name="columnname" select="'location/city'" />
I want to pass the result of getNodeValue into quotevalue so that the result is properly quoted.
The XSLT:
<?xml version="1.0"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:csv="csv:csv" xpath-default-namespace="http://nowhere/" >
<xsl:output method="text" encoding="utf-8" />
<xsl:strip-space elements="*" />
<xsl:variable name="delimiter" select="','" />
<csv:columns>
<column>title</column>
<column>location/city</column>
</csv:columns>
<xsl:template match="job">
<xsl:value-of select="concat(#id, ',')"/>
<!-- #1 I WANT TO LOOP THROUGH ALL OF THE CSV COLUMNS HERE -->
<!-- #2 How do I put the text into the variable 'columnname' variable so that it works with getNodeValue? -->
<xsl:variable name="columnname" select="'location/city'" />
<xsl:variable name="vXpathExpression" select="$columnname"/>
<xsl:call-template name="getNodeValue">
<xsl:with-param name="pExpression" select="$vXpathExpression"/>
</xsl:call-template>
<!-- #3 After getNodeValue gets the value, I want to send that value into 'quotevalue' -->
<xsl:text>
</xsl:text>
</xsl:template>
<xsl:template name="getNodeValue">
<xsl:param name="pExpression"/>
<xsl:param name="pCurrentNode" select="."/>
<xsl:choose>
<xsl:when test="not(contains($pExpression, '/'))">
<xsl:value-of select="$pCurrentNode/*[name()=$pExpression]"/>
</xsl:when>
<xsl:otherwise>
<xsl:call-template name="getNodeValue">
<xsl:with-param name="pExpression"
select="substring-after($pExpression, '/')"/>
<xsl:with-param name="pCurrentNode" select=
"$pCurrentNode/*[name()=substring-before($pExpression, '/')]"/>
</xsl:call-template>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
<xsl:template name="quotevalue">
<xsl:param name="value"/>
<xsl:choose>
<!-- Quote the value if required -->
<xsl:when test="contains($value, '"')">
<xsl:variable name="x" select="replace($value, '"', '""')"/>
<xsl:value-of select="concat('"', $x, '"')"/>
</xsl:when>
<xsl:when test="contains($value, $delimiter)">
<xsl:value-of select="concat('"', $value, '"')"/>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="$value"/>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
Sample XML
<?xml version="1.0" encoding="utf-8"?>
<positionfeed
xmlns="http://nowhere/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
version="2006-04">
<job id="2830302">
<employer>Acme</employer>
<title>Manager</title>
<description>Full time</description>
<postingdate>2016-09-15T23:12:13Z</postingdate>
<location>
<city>Los Angeles</city>
<state>California</state>
</location>
</job>
<job id="2830303">
<employer>Acme</employer>
<title>Clerk, evenings</title>
<description>Part time</description>
<postingdate>2016-09-15T23:12:13Z</postingdate>
<location>
<city>Albany</city>
<state>New York</state>
</location>
</job>
</positionfeed>
The current output using the XSLT I provided
2830302,Los Angeles
2830303,Albany
The output if the XSLT works as desired
2830302,Manager,Los Angeles
2830303,"Clerk, evenings",Albany
Solution (many thanks to Tim's help below)
<?xml version="1.0"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:csv="csv:csv" xpath-default-namespace="http://www.job-search-engine.com/add-jobs/positionfeed-namespace/" >
<xsl:output method="text" encoding="utf-8" />
<xsl:strip-space elements="*" />
<!-- Set the value of the delimiter character -->
<xsl:variable name="delimiter" select="','" />
<!-- The name of the node that contains the column values -->
<xsl:param name="containerNodeName" select="'job'"/>
<!-- All nodes that should be ignored during processing -->
<xsl:template match="source|feeddate"/>
<!-- The names of the nodes to be included in the CSV file -->
<xsl:variable name="columns" as="element()*">
<column header="Title">title</column>
<column header="Category">category</column>
<column header="Description">description</column>
<column header="PostingDate">postingdate</column>
<column header="URL">joburl</column>
<column header="City">location/city</column>
<column header="State">location/state</column>
</xsl:variable>
<!-- ************** DO NOT TOUCH BELOW **************** -->
<!-- ************** DO NOT TOUCH BELOW **************** -->
<!-- ************** DO NOT TOUCH BELOW **************** -->
<!-- ************** DO NOT TOUCH BELOW **************** -->
<!-- ************** DO NOT TOUCH BELOW **************** -->
<!-- Warn about unmatched nodes -->
<xsl:template match="*">
<xsl:message terminate="no">
<xsl:text>WARNING: Unmatched element: </xsl:text>
<xsl:value-of select="name()"/>
</xsl:message>
<xsl:apply-templates/>
</xsl:template>
<!-- Generate the column headers -->
<xsl:template match="//*[*[local-name()=$containerNodeName]]">
<xsl:value-of select="'Id'"/>
<xsl:value-of select="$delimiter"/>
<xsl:for-each select="$columns/#header">
<xsl:variable name="colname" select="." />
<xsl:value-of select="$colname"/>
<xsl:if test="position() != last()">
<xsl:value-of select="$delimiter"/>
</xsl:if>
</xsl:for-each>
<xsl:text>
</xsl:text>
<xsl:apply-templates />
</xsl:template>
<!-- Generate the rows of column data -->
<xsl:template match="//*[local-name()=$containerNodeName]">
<!-- TODO: Handle attributes generically -->
<xsl:value-of select="#id"/>
<xsl:variable name="container" select="." />
<xsl:for-each select="$columns">
<xsl:value-of select="$delimiter"/>
<xsl:variable name="vXpathExpression" select="."/>
<xsl:call-template name="getQuotedNodeValue">
<xsl:with-param name="pCurrentNode" select="$container"/>
<xsl:with-param name="pExpression" select="$vXpathExpression"/>
</xsl:call-template>
</xsl:for-each>
<xsl:text>
</xsl:text>
</xsl:template>
<xsl:template name="getQuotedNodeValue">
<xsl:param name="pExpression"/>
<xsl:param name="pCurrentNode" select="."/>
<xsl:choose>
<xsl:when test="not(contains($pExpression, '/'))">
<xsl:variable name="result" select="$pCurrentNode/*[name()=$pExpression]"/>
<xsl:call-template name="quotevalue">
<xsl:with-param name="value" select="$result"/>
</xsl:call-template>
</xsl:when>
<xsl:otherwise>
<xsl:call-template name="getQuotedNodeValue">
<xsl:with-param name="pExpression" select="substring-after($pExpression, '/')"/>
<xsl:with-param name="pCurrentNode" select= "$pCurrentNode/*[name()=substring-before($pExpression, '/')]"/>
</xsl:call-template>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
<xsl:template name="quotevalue">
<xsl:param name="value"/>
<xsl:choose>
<xsl:when test="contains($value, '"')">
<!-- Quote the value and escape the double-quotes -->
<xsl:variable name="x" select="replace($value, '"', '""')"/>
<xsl:value-of select="concat('"', $x, '"')"/>
</xsl:when>
<xsl:otherwise>
<!-- Quote the value -->
<xsl:value-of select="concat('"', $value, '"')"/>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
</xsl:stylesheet>
Sample data to demonstrate solution
<?xml version="1.0" encoding="utf-8"?>
<positionfeed
xmlns="http://www.job-search-engine.com/add-jobs/positionfeed-namespace/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.job-search-engine.com/add-jobs/positionfeed-namespace/ http://www.job-search-engine.com/add-jobs/positionfeed.xsd"
version="2006-04">
<source>Casting360</source>
<feeddate>2016-11-11T21:48:34Z</feeddate><job id="1363612">
<employer>Casting360</employer>
<title>The Robert Irvine Show Is Seeking Guests</title>
<category>Reality TV</category>
<description>TV personality ROBERT IRVINE (Restaurant Impossible) is seeking guests looking for solutions to their unique problems to share their stories on his show!
Our next show is Thursday, September 22nd in LA. If you're not in LA we will provide your airfare, hotel, car service, and per diem.
Please note: WE ARE NOT LOOKING FOR RESUMES; THIS IS NOT AN ACTING GIG. We are looking for real people to share their stories!
*appearance fee (TBD)
If you or someone you know has a conflict that they need help resolving, WE WANT TO HEAR FROM YOU.
Please email tvgal.ri#gmail.com the following information:
Name
Phone number
Your story in 2-3 paragraphs
1-3 photos of yourself.</description>
<postingdate>2016-09-15T23:12:13Z</postingdate>
<joburl>http://casting360.com/lgj/8886644624?jobid=1363612&city=Los+Angeles&state=CA</joburl>
<location>
<nation>USA</nation>
<city>Los Angeles</city>
<state>California</state>
</location>
<jobsource>Casting360</jobsource>
</job><job id="1370302">
<employer>Casting360</employer>
<title>Photoshoot for Publication</title>
<category>Modeling</category>
<description>6 FEMALE Models are wanted for publication photoshoot.
If you're not in the NYC Vicinity (NY, Pa, Ct,) DO NOT REPLY because your response will be summarily ignored.
Chosen models will be given a 5 look photo shoot. The shoot will occur on location (outdoors) in highly public locations chosen both for it's convenience and scenery.
The 5 looks (outfits) will be pre-determined by our staff of items most outfits within a model's wardrobe.
THIS IS A TF (UNPAID) SHOOT. After the release of the magazine, the photos agreed upon from the shoot shall be given to the model (in digital format) for her to build her portfolio.
Chosen models will receive a 5 outfit photo shoot at no cost to them by a NY Fashion Photographer.As a result, chosen models not only receive a free photo shoot, but also become PUBLISHED MODELS featured in a magazine.
The model (Janeykay) centered in the photo attached (Please look at the attached photo) is a Casting360 member who not only received her photo shoot, not only is being featured in a magazine, but also made the cover becoming a Cover Model from her shoot with us.</description>
<postingdate>2016-10-03T00:34:43Z</postingdate>
<joburl>http://casting360.com/lgj/8886644624?jobid=1370302&city=New+York&state=NY</joburl>
<location>
<nation>USA</nation>
<city>New York</city>
<state>New York</state>
</location>
<jobsource>Casting360</jobsource>
</job><job id="1370962">
<employer>Casting360</employer>
<title>Actresses Needed for "Red Shore", Action Film</title>
<category>Acting</category>
<description>CASTING (non-union)
We are a New Independent company looking to shoot our first feature. We are currently looking to fill two Major roles.
Female/African American, Hispanic, Asian, Pacific Islander/ 5'5-5'10/ Age Late 30's-Early 40's.
Project description: A long standing feud between two best friends turned enemies escalates over a valuable Diamond on display in a New York City Museum. With the stakes high they each seek the help of both friends and strangers to settle their feud once and for all.
Please note this is a non-paid project.
Fight training will be provided for free.
Please email including age and height in your e-mail.
Those selected will be invited to our audition.</description>
<postingdate>2016-10-03T14:18:20Z</postingdate>
<joburl>http://casting360.com/lgj/8886644624?jobid=1370962&city=New+York&state=NY</joburl>
<location>
<nation>USA</nation>
<city>New York</city>
<state>New York</state>
</location>
<jobsource>Casting360</jobsource>
</job>
</positionfeed>
As you are using XSLT 2.0, you could define your columns in a variable like so:
<xsl:variable name="columns" as="element()*">
<column>title</column>
<column>location/city</column>
</xsl:variable>
Then you can just iterate over them with a simple statement
<xsl:for-each select="$columns">
But the problem you may be having is that within this xsl:for-each you have changed context. You are no longer positioned on a job element, but the column element, and you don't want your expression to be relative to that. You really need to swap back to being on the job element, which you can do simply by setting a variable reference to the job element before the xsl:for-each and then using that as a parameter to the named template:
<xsl:template match="job">
<xsl:value-of select="#id"/>
<xsl:variable name="job" select="." />
<xsl:for-each select="$columns">
<xsl:value-of select="$delimiter"/>
<xsl:variable name="vXpathExpression" select="."/>
<xsl:call-template name="getNodeValue">
<xsl:with-param name="pCurrentNode" select="$job"/>
<xsl:with-param name="pExpression" select="$vXpathExpression"/>
</xsl:call-template>
</xsl:for-each>
<xsl:text>
</xsl:text>
</xsl:template>
As for quoting the result; instead of doing just xsl:value-of simply call the quote template with the value as a parameter
<xsl:when test="not(contains($pExpression, '/'))">
<xsl:call-template name="quotevalue">
<xsl:with-param name="value" select="$pCurrentNode/*[name()=$pExpression]" />
</xsl:call-template>
</xsl:when>
EDIT: If you want a header row of column names, you would have to match the parent of the job node, and then just output the values of the $column variable
<xsl:template match="*[job]">
<xsl:value-of select="$columns" separator="," />
<xsl:text>
</xsl:text>
<xsl:apply-templates />
</xsl:template>
Or maybe this if you didn't want the full path
<xsl:value-of select="$columns/(tokenize(., '/')[last()])" separator="," />
Or you could extend your columns variable to have the header text
<xsl:variable name="columns" as="element()*">
<column header="Title">title</column>
<column header="City">location/city</column>
</xsl:variable>
Then you would do this...
<xsl:value-of select="$columns/#header" separator="," />

XSLT: Concatenate and select the element

XSLT:
Written my XSLT like this but I'm not getting required output as below that means I want to loop through each record and get frontimagefilename and rearimagefilename for each check.
<xsl:template name="ChequeDetailsTemplate">
<xsl:param name ="vItemcurrIndx" />
<xsl:variable name ="x" select ="$allRecs[$vItemcurrIndx]/Content/*" />
<xsl:call-template name="loop">
<xsl:with-param name="i" select="1"/>
<xsl:with-param name="limit" select="$x/NumberOfCheques"/>
<xsl:with-param name="vItemcurrIndx" select="position()"></xsl:with-param>
</xsl:call-template>
</xsl:template>
<xsl:template name="loop">
<xsl:param name="i"/>
<xsl:param name="limit"/>
<xsl:param name ="vItemcurrIndx" />
<xsl:variable name ="y" select ="$allRecs[$vItemcurrIndx]/Content/*" />
<xsl:if test="$i <= $limit">
<Check>
<CheckAmount><xsl:value-of select="concat(./CourtesyAmount,$i)"/> </CheckAmount>
<FrontImage><xsl:value-of select="concat(./FrontImageFilename,$i)"/></FrontImage>
<RearImage><xsl:value-of select="concat(./RearImageFilename,$i)"/></RearImage>
</Check>
<xsl:call-template name="loop">
<xsl:with-param name="i" select="$i+1"/>
<xsl:with-param name="limit" select="$limit"/>
</xsl:call-template>
</xsl:if>
</xsl:template>
Output looking for:
-<Check><CheckAmount>300</CheckAmount><Codeline><006474< :########## 12345678<</Codeline><FrontImage>C:\Jan292015\archive (1) - Copy\archive\BIN\TempChequeImages\CHQNCR-2VD8NP348TD20150129135318f001.tif</FrontImage><RearImage>C:\Jan292015\archive (1) - Copy\archive\BIN\TempChequeImages\CHQNCR-2VD8NP348TD20150129135318r001.tif</RearImage><CourtesyAmount>300</CourtesyAmount></Check>-<Check><CheckAmount>300</CheckAmount><Codeline><006474< :########## 12345678<</Codeline><FrontImage>C:\Jan292015\archive (1) - Copy\archive\BIN\TempChequeImages\CHQNCR-2VD8NP348TD20150129135320f002.tif</FrontImage><RearImage>C:\Jan292015\archive (1) - Copy\archive\BIN\TempChequeImages\CHQNCR-2VD8NP348TD20150129135320r002.tif</RearImage><CourtesyAmount>300</CourtesyAmount></Check>
But the output which im getting now is:
-<Check><CheckAmount>1</CheckAmount><FrontImage>1</FrontImage><RearImage>1</RearImage></Check>-<Check><CheckAmount>2</CheckAmount><FrontImage>2</FrontImage><RearImage>2</RearImage></Check>
If I am guessing (!) correctly, your input looks something like this:
<ChqDepAppSrvChequeScanComplete>
<CourtesyAmount1>100</CourtesyAmount1>
<FrontImageFilename1 t="String">R:\bin_simulated\Images\TempChequeImages\100f001.bmp</FrontImageFilename1>
<RearImageFilename1 t="String">R:\bin_simulated\Images\TempChequeImages\100r001.bmp</RearImageFilename1>
<RefuseReason1 t="String">None</RefuseReason1>
<CourtesyAmount2>200</CourtesyAmount2>
<FrontImageFilename2 t="String">R:\bin_simulated\Images\TempChequeImages\200f002.bmp</FrontImageFilename2>
<RearImageFilename2 t="String">R:\bin_simulated\Images\TempChequeImages\200r002.bmp</RearImageFilename2>
<RefuseReason2 t="String">None</RefuseReason2>
<NumberOfCheques t="Int32">2</NumberOfCheques>
</ChqDepAppSrvChequeScanComplete>
Your mistake is in the way you have built this expression:
<xsl:value-of select="concat(./CourtesyAmount,$i)"/>
There is no <CourtesyAmount> node in your input, so you are concatenating nothing and $i, resulting in the current value of $i.
What you really want to do here is get the value from a node whose name is the concatenation of the string "CourtesyAmount" and the current value of $i. Something like:
XSLT 1.0
<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="/ChqDepAppSrvChequeScanComplete">
<output>
<xsl:call-template name="loop">
<xsl:with-param name="limit" select="NumberOfCheques"/>
</xsl:call-template>
</output>
</xsl:template>
<xsl:template name="loop">
<xsl:param name="i" select="1"/>
<xsl:param name="limit"/>
<xsl:if test="$i <= $limit">
<Check>
<CheckAmount>
<xsl:value-of select="*[local-name()=concat('CourtesyAmount', $i)]"/>
</CheckAmount>
<FrontImage>
<xsl:value-of select="*[local-name()=concat('FrontImageFilename', $i)]"/>
</FrontImage>
<RearImage>
<xsl:value-of select="*[local-name()=concat('RearImageFilename', $i)]"/>
</RearImage>
</Check>
<xsl:call-template name="loop">
<xsl:with-param name="i" select="$i+1"/>
<xsl:with-param name="limit" select="$limit"/>
</xsl:call-template>
</xsl:if>
</xsl:template>
</xsl:stylesheet>
which when applied to the above input will result in:
<?xml version="1.0" encoding="UTF-8"?>
<output>
<Check>
<CheckAmount>100</CheckAmount>
<FrontImage>R:\bin_simulated\Images\TempChequeImages\100f001.bmp</FrontImage>
<RearImage>R:\bin_simulated\Images\TempChequeImages\100r001.bmp</RearImage>
</Check>
<Check>
<CheckAmount>200</CheckAmount>
<FrontImage>R:\bin_simulated\Images\TempChequeImages\200f002.bmp</FrontImage>
<RearImage>R:\bin_simulated\Images\TempChequeImages\200r002.bmp</RearImage>
</Check>
</output>
Note:
The real problem here is the input. It should not be formatted this way. Things would be much easier if the person ahead of you did a proper job and supplied you with a well-structured XML, for example:
<ChqDepAppSrvChequeScanComplete>
<NumberOfCheques t="Int32">2</NumberOfCheques>
<Cheque>
<CourtesyAmount>100</CourtesyAmount>
<FrontImageFilename t="String">R:\bin_simulated\Images\TempChequeImages\100f001.bmp</FrontImageFilename>
<RearImageFilename t="String">R:\bin_simulated\Images\TempChequeImages\100r001.bmp</RearImageFilename>
<RefuseReason t="String">None</RefuseReason>
</Cheque>
<Cheque>
<CourtesyAmount>200</CourtesyAmount>
<FrontImageFilename t="String">R:\bin_simulated\Images\TempChequeImages\200f002.bmp</FrontImageFilename>
<RearImageFilename t="String">R:\bin_simulated\Images\TempChequeImages\200r002.bmp</RearImageFilename>
<RefuseReason t="String">None</RefuseReason>
</Cheque>
</ChqDepAppSrvChequeScanComplete>
with none of this numbered nodes nonsense.

Split Attribute using ; as delimiter in XSLT

How to split an elements using ; as delimiter.my requirement is like below.
input:
<Element1>C:KEK39519US; U:085896395195; A:K39519US; B:S2345843</Element1>
output:
<CustItem>KEK39519US</CustItem>
<UNumber>085896395195</UNumber>
<ANumber>K39519US</ANumber>
<BNumber>S2345843</BNumber>
the input is every time not same.some times it comes like C:KEK39519US; U:085896395195; B:S2345843
some time like this C:KEK39519US; A:K39519US; B:S2345843
sometime like this U:085896395195; A:K39519US;
sometime like this C:KEK39519US; U:085896395195; A:K39519US;
To solve this in XSLT 1.0 you may need a named template which recursively calls itself. The template will process of the string before the first semi-colon, and output the element accordingly. It will then recursively call itself with the remaining part of the string after this semi-colon (if there is one)
Here is the full XSLT
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="Element1">
<xsl:call-template name="outputElements">
<xsl:with-param name="list" select="." />
</xsl:call-template>
</xsl:template>
<xsl:template name="outputElements">
<xsl:param name="list"/>
<xsl:variable name="first" select="normalize-space(substring-before(concat($list, ';'), ';'))"/>
<xsl:variable name="remaining" select="normalize-space(substring-after($list, ';'))"/>
<xsl:call-template name="createElement">
<xsl:with-param name="element" select="$first" />
</xsl:call-template>
<!-- If there are still elements left in the list, call the template recursively -->
<xsl:if test="$remaining">
<xsl:call-template name="outputElements">
<xsl:with-param name="list" select="$remaining"/>
</xsl:call-template>
</xsl:if>
</xsl:template>
<xsl:template name="createElement">
<xsl:param name="element"/>
<xsl:variable name="elementName">
<xsl:choose>
<xsl:when test="substring-before($element, ':') = 'C'">CustItem</xsl:when>
<xsl:otherwise><xsl:value-of select="concat(substring-before($element, ':'), 'Number')" /></xsl:otherwise>
</xsl:choose>
</xsl:variable>
<xsl:element name="{$elementName}">
<xsl:value-of select="substring-after($element, ':')" />
</xsl:element>
</xsl:template>
</xsl:stylesheet>
When applied to you XML, the following is output
<CustItem>KEK39519US</CustItem>
<UNumber>085896395195</UNumber>
<ANumber>K39519US</ANumber>
<BNumber>S2345843</BNumber>
Note the use of Attribute Value Templates in specifying the name of each new element.

Generate a breadcrumb trail with xsl from a node structure

I have difficulties to write a template that generates a breadcrumb trial out of a node structure. It is not working correctly up to now, there is some flaw in my thinking how it should walk the item path.
Consider the following page structure:
<!-- ===== SITE PAGE STRUCTURE ===================================== -->
<index>
<item section="home" id="index"></item>
<item section="service" id="index">
<item id="content-management-systems">
<item id="p1-1"/>
<item id="p1-2"/>
<item id="p1-3"/>
</item>
<item id="online-stores"></item>
<item id="search-engines-and-ir"></item>
<item id="web-applications"></item>
</item>
<item section="solutions" id="index">
<item id="document-clustering"></item>
</item>
<item section="company" id="index">
<item section="company" id="about"></item>
<item section="company" id="philosophy" ></item>
...
</item>
...
</item>
This site index represents a site-structure of xml content pages in its hierarchy (consider it to be a menu). It contains of sections, that represent the site sections just as home, company, service, solutions, etc. These sections can contain sub-sections with pages, or just regular content pages. A content page (its xml contents such as title, text content, etc) is identified by the #id attribute in the item tree. The #id attribute mainly is used to fetch the content of the entire page that will be rendered to html.
The breadcrumb template uses the item node #id attribute to get the title of the page (which will be shown in the breadcrumb trail).
I try to implement the following template that walks the tree by checking the target section attribute #section and the target page attribute #id in the tree. I expect it to walk the axis down until the target item_target is found by comparing the ancestors #section attribute and the #id with $item_target of each node in that axis.
For example: Attribute *$item_section=service* and the page id *target item_target=p1-1* should now recursively "walk" to the section branch "service" (depth 1), check if the target page #id is found on this level. In this case it is not found, so it makes the next recurive call (via apply-templates) to the next item node level (in this case it would be content-management-systems, there the target item page p1-1 is found, so the trail process is finished:
The result should like this:
home >> service >> content management systems >> p1-1
But unfortunately it is not working correct, at least not in every case. Also maybe it can be solved more easily. I try to implement it as an recursive template that walks from the top (level 0) to the target page (item node) as a leaf.
<!-- walk item path to generate a breadcrumb trail -->
<xsl:template name="breadcrumb">
<a>
<xsl:attribute name="href">
<xsl:text>/</xsl:text>
<xsl:value-of select="$req-lg"/>
<xsl:text>/home/index</xsl:text>
</xsl:attribute>
<xsl:value-of select="'Home'"/>
</a>
<xsl:apply-templates select="$content/site/index" mode="Item-Path">
<xsl:with-param name="item_section" select="'service'"/>
<xsl:with-param name="item_target" select="'search-engines-and-ir'"/>
<xsl:with-param name="depth" select="0"/>
</xsl:apply-templates>
</xsl:template>
<xsl:template match="item" mode="Item-Path">
<xsl:param name="item_section" />
<xsl:param name="item_target" />
<xsl:param name="depth" />
<!--
depth=<xsl:value-of select="$depth"/>
count=<xsl:value-of select="count(./node())"/><br/>
-->
<xsl:variable name="cur-id" select="#id"/>
<xsl:variable name="cur-section" select="#section"/>
<xsl:choose>
<xsl:when test="#id=$item_target">
>>
<a>
<xsl:attribute name="href">
<xsl:text>/</xsl:text>
<!-- req-lg: global langauge variable -->
<xsl:value-of select="$req-lg"/>
<xsl:text>/</xsl:text>
<xsl:value-of select="$item_section"/>
<xsl:text>/</xsl:text>
<xsl:if test="$depth = 2">
<xsl:value-of select="../#id"/>
<xsl:text>/</xsl:text>
</xsl:if>
<xsl:value-of select="#id"/>
</xsl:attribute>
<xsl:value-of
select="$content/page[#id=$cur-id]/title"/>
</a>
</xsl:when>
<xsl:otherwise>
<xsl:if test="ancestor-or-self::item/#section = $item_section and count(./node()) > 0">
>>:
<a>
<xsl:attribute name="href">
<xsl:text>/</xsl:text>
<!-- req-lg: global langauge variable -->
<xsl:value-of select="$req-lg"/>
<xsl:text>/</xsl:text>
<xsl:value-of select="$item_section"/>
<xsl:text>/</xsl:text>
<xsl:if test="$depth = 2">
<xsl:value-of select="../#id"/>
<xsl:text>/</xsl:text>
</xsl:if>
<xsl:value-of select="#id"/>
</xsl:attribute>
<xsl:value-of
select="$content/page[#id=$cur-id and #section=$item_section]/title"/>
</a>
</xsl:if>
</xsl:otherwise>
</xsl:choose>
<xsl:apply-templates select="item" mode="Item-Path">
<xsl:with-param name="item_section" select="$item_section"/>
<xsl:with-param name="item_target" select="$item_target"/>
<xsl:with-param name="depth" select="$depth + 1"/>
</xsl:apply-templates>
</xsl:template>
So as the hardcoded parameters in the template breadcrumb, target section = 'service' and target page = 'search-engines-and-ir', I expect an output like
home >> service >> search-engines-and-ir
But the output is
home >> service >> content-management-systems >> search-engines-and-ir
which is obviously not correct.
Can anybody give me a hint how to correct this issue? It would be even more elegant to avoid that depth checking, but up to now I cannot think of a other way, I am sure there is a more elegant solution.
I work with XSLT 1.0 (libxml via PHP5).
Hope my question is clear enough, if not, please ask :-) Thanks for the help in advance!
As simple as this:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text"/>
<xsl:key name="kNodeById" match="item" use="#id"/>
<xsl:template match="/">
<xsl:text>home</xsl:text>
<xsl:call-template name="findPath">
<xsl:with-param name="pStart" select="'service'"/>
<xsl:with-param name="pEnd" select="'search-engines-and-ir'"/>
</xsl:call-template>
</xsl:template>
<xsl:template name="findPath">
<xsl:param name="pStart"/>
<xsl:param name="pEnd"/>
<xsl:for-each select=
"key('kNodeById', $pEnd)
[ancestor::item[#section=$pStart]]
[1]
/ancestor-or-self::item
[not(descendant::item[#section=$pStart])]
">
<xsl:value-of select=
"concat('>>', #id[not(../#section)], #section)"/>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
the wanted, correct result is produced:
home>>service>>search-engines-and-ir
Do Note:
This solution prints the breadcrumb from any node -- anywhere in the hierarchy to any of its descendent nodes -- anywhere in the hierarchy. More precisely, for the first item (in document order) with id attribute equal to $pEnd, the breadcrumb is generated from its inner-most ancestor whose section attribute is equal to $pStart -- to that item element.
This solution should be much more efficient than any solution using //, because we are using a key to locate efficiently the "end" item element.
II. XSLT 2.0 solution:
Much shorter and easier -- an XPathe 2.0 single expression:
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text"/>
<xsl:key name="kNodeById" match="item" use="#id"/>
<xsl:template match="/">
<xsl:value-of select=
"string-join(
(
'home',
key('kNodeById', $pEnd)
[ancestor::item[#section=$pStart]]
[1]
/ancestor-or-self::item
[not(descendant::item[#section=$pStart])]
/(#id[not(../#section)], #section)[1]
),
'>>'
)
"/>
</xsl:template>
</xsl:stylesheet>
You can just iterate over the ancestor-or-self:: axis . This is easy to do without recursion. For example...
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html"/>
<xsl:template match="/">
<html><body>
<xsl:call-template name="bread-crumbs">
<xsl:with-param name="items" select="*/item" />
<xsl:with-param name="section" select="'service'" />
<xsl:with-param name="leaf" select="'p1-2'" />
</xsl:call-template>
</body></html>
</xsl:template>
<xsl:template name="bread-crumbs">
<xsl:param name="items" />
<xsl:param name="section" />
<xsl:param name="leaf" />
<xsl:value-of select="concat($section,'>>')" />
<xsl:for-each select="$items/self::item[#section=$section]//item[#id=$leaf]/
ancestor-or-self::item[not(#section)]">
<xsl:value-of select="#id" />
<xsl:if test="position() != last()">
<xsl:value-of select="'>>'" />
</xsl:if>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
...on your sample input yields...
<html>
<body>service>>content-management-systems>>p1-2</body>
</html>
...which renders as...
service>>content-management-systems>>p1-2

unique values of multi-token string using xslt

I have xml like
<programs>
<program name="breaking laws" id="97;#ttt;#98;#tpl;#41;#fel" />
<program name="advanced technology" id="89;#hjk;#95;#uio;#81;#lpk" />
<program name="Emerging companies " id="88;#ple;#98;#tpl;#41;#fel" />
<program name="breakinglaws" id="97;#ttt" />
<program name="breakinglaws" id="97;#ttt;#98;#tpl;#81;#lpk" />
<program name="breakinglaws" id="99;#hklo;#95;#uio" />
</programs>
I would like to find all the unique ids text using xslt 1.0 i.e
ttt
tpl
fel
hjk
uio
lpk
ple
hklo
I was trying to do something using key and output tokens
<xsl:template name="output-tokens">
<xsl:param name="list" />
<xsl:variable name="newlist" select="concat(normalize-space($list), ' ')" />
<xsl:variable name="first" select="substring-before($newlist, ';#')" />
<xsl:variable name="remaining" select="substring-after($newlist, ';#')" />
<id>
<xsl:value-of select="$first" />
</id>
<xsl:if test="$remaining">
<xsl:call-template name="output-tokens">
<xsl:with-param name="list" select="$remaining" />
</xsl:call-template>
</xsl:if>
</xsl:template>
Here is one solution
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="/programs">
<!-- Variable containing concateneated list of all program elements**
<xsl:variable name="allprograms">
<xsl:apply-templates select="program"/>
</xsl:variable>
<!-- Call recursive template to split the list -->
<xsl:call-template name="output-tokens">
<xsl:with-param name="list" select="$allprograms" />
</xsl:call-template>
</xsl:template>
<!-- Template used to concatenate all program elements -->
<xsl:template match="program">
<xsl:value-of select="concat(#id, ';#') "/>
</xsl:template>
<!-- Recursive template to split out list into unique elements -->
<xsl:template name="output-tokens">
<!-- List to split -->
<xsl:param name="list"/>
<!-- List of all currently processed elements -->
<xsl:param name="newlist" select="';#'" />
<!-- Get first variable in list, and also the remaining part of the list -->
<xsl:variable name="first" select="substring-before($list, ';#')"/>
<xsl:variable name="remaining" select="substring-after($list, ';#')"/>
<!-- Check if first variable is not a number, and is not contained in currently processed list -->
<xsl:if test="number($first) != number($first) and not(contains($newlist, concat(';#', $first, ';#')))">
<id>
<xsl:value-of select="$first"/>
</id>
</xsl:if>
<!-- If there are still elements left in the list, call the template recursively -->
<xsl:if test="$remaining">
<xsl:call-template name="output-tokens">
<xsl:with-param name="list" select="$remaining"/>
<xsl:with-param name="newlist" select="concat($newlist, $first, ';#')"/>
</xsl:call-template>
</xsl:if>
</xsl:template>
</xsl:stylesheet>
The idea is you first build up a single string containing all the program elements concatenated together. You then call a recursive template which gets the first element from the list, and then checks it has not already been processed (this is achieved by the template also containing a variable of already processed elements)
When the XSLT is applied to your sample XML, the following is output:
<id>ttt</id>
<id>tpl</id>
<id>fel</id>
<id>hjk</id>
<id>uio</id>
<id>lpk</id>
<id>ple</id>
<id>hklo</id>