Select substrings dependent on context - xslt

I have this piece of XML and want to get the number immediately after Chapter
<para>Insolvency Rules, r 12.12, which gives the court a broad discretion, unfettered by the English equivalent of the heads of Order 11, r 1(1) (which are now to be found, in England, in CPR, Chapter 6, disapplied in the insolvency context by Insolvency Rules, r 12.12(1)). </para>
When I used this XSLT transform
<xsl:value-of select="translate(substring-after(current(),'Chapter'), translate(substring-after(current(),'Chapter'),'0123456789',''), '')"/>
I get this output
612121
Butut I want just 6.
Please let me know how I should do it.
I don't want to use a statement like
<xsl:value-of select="substring-before(substring-after(current(),'Chapter'), ,',')"/>
as the chapter number will be different in each instance, between 1 and 15.

Try this:
<xsl:variable name="vS" select="concat(substring-after(current(),'Chapter '),'Z')"/>
<xsl:value-of select=
"substring-before(translate($vS,translate($vS,'0123456789',''),'Z'),'Z')"/>
This is based on: https://stackoverflow.com/a/4188249/2115381 Thanks to
#Dimitre Novatchev
Update: If the quantity of space after the "Chapter" is not known you can use something like this:
<xsl:variable name="vS" select="concat(substring-after(current(),'Chapter'),'Z')"/>
<xsl:value-of select=
" translate(
substring-before(translate($vS,translate($vS,' 0123456789',''),'Z'),'Z')
, ' ','')"/>

Related

Looping through an xpath getting the right iteration each time in xslt 2

I have a condition where I need to loop atleast once and so I have the following xsl code. However, this doesnt work as it always gets the last iterations value. How can I tweak this so it gets the right iteration on each loop?
<xsl:variable name='count0'>
<xsl:choose>
<xsl:when test='count($_BoolCheck/BoolCheck[1]/CheckBoolType) = 0'>
<xsl:value-of select="1"/>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select='count($_BoolCheck/BoolCheck[1]/CheckBoolType)'/>
</xsl:otherwise>
</xsl:choose>
</xsl:variable>
<xsl:for-each select="1 to $count0">
<xsl:variable name='_LoopVar_2_0' select='$_BoolCheck/BoolCheck[1]/CheckBoolType[position()=$count0]'/>
<e>
<xsl:attribute name="n">ValueIsTrue</xsl:attribute>
<xsl:attribute name="m">f</xsl:attribute>
<xsl:attribute name="d">f</xsl:attribute>
<xsl:if test="(ctvf:isTrue($_LoopVar_2_0/CheckBoolType[1]))">
<xsl:value-of select=""Value True""/>
</xsl:if>
</e>
</xsl:for-each>
The xml file is as follows:
<BoolCheck>
<CheckBoolType>true</CheckBoolType>
<CheckBoolType>false</CheckBoolType>
<CheckBoolType>1</CheckBoolType>
<CheckBoolType>0</CheckBoolType>
<CheckBoolType>True</CheckBoolType>
<CheckBoolType>False</CheckBoolType>
<CheckBoolType>TRUE</CheckBoolType>
<CheckBoolType>FALSE</CheckBoolType>
</BoolCheck>
In this case I need to iterate through each iteration of CheckBoolType and produce a corresponding number of values. However, in the above example if there were no CheckBoolType iterations I would still like the iterations to enter the for-each loop atleast once. i hope that clarifies it a little more.
First observation: your declaration of $count0 can be replaced by
<xsl:variable name="temp" select="count($_BoolCheck/BoolCheck[1]/CheckBoolType)"/>
<xsl:variable name="count0" select="if ($temp=0) then 1 else $temp"/>
(Sorry if that seems irrelevant, but my first step in debugging code is always to simplify it. It makes the bugs much easier to find).
When you do this you can safely replace the predicate [position()=$count0] by [$count0], because $count0 is now an integer rather than a document node. (Even better, declare it as an integer using as='xs:integer' on the xsl:variable declaration.)
But hang on, $count0 is the number of elements being processed, so CheckBoolType[$count] will always select the last one. That's surely not what you want.
This brings us to another bug in your code. The value of the variable $_LoopVar_2_0 is an element node named CheckBoolType. The expression $_LoopVar_2_0/CheckBoolType[1] is looking for children of this element that are also named CheckBoolType. There are no such children, so the expression selects an empty sequence, so the boolean test is always false.
At this stage I would like to show you some correct code to achieve your desired output. Unfortunately you haven't shown us the desired output. I can't reverse engineer the requirement from (a) your incorrect code, and (b) your prose description of the algorithm you are trying to implement.

Inconsistency in nodeset test?

I have an XML with top-level elements in this vein:
<chapter template="one"/>
<chapter template="two"/>
<chapter template="one"/>
<chapter template="one"/>
<chapter template="two"/>
<chapter template="one"/>
I'm processing these elements by looping through them with a choose statement:
<xsl:variable name="layout" select="#template"/>
<xsl:choose>
<xsl:when test="contains($layout, 'one')">
<xsl:call-template name="processChapterOne"/>
</xsl:when>
<xsl:when test="contains($layout, 'two')">
<xsl:call-template name="processChaptertwo"/>
</xsl:when>
<xsl:otherwise/>
</xsl:choose>
This works correctly. But now I'm trying to do some conditional processing, so I'm trying to find the first chapter in the list:
<xsl:when test="count(preceding-sibling::*[($layout = 'one')]) = '0'">
<xsl:call-template name="processChapterOne"/>
</xsl:when>
Here's when things get weird. My test never becomes true: the value of count(...) is 4 for the first chapter in the list, and increments from there. It looks like it counts all of the top-level elements, and not just the ones named 'chapter'.
When I change the code to this:
<xsl:when test="count(preceding-sibling::*[(#template = 'one')]) = '0'">
<xsl:call-template name="processChapterOne"/>
</xsl:when>
it works correctly. So I've replaced a variable with a direct reference. I can't figure out why this would make a difference. What could cause this?
The not working and working cases are actually very different:
Not working: In preceding-sibling::*[$layout = 'one'], $layout is always the same value of one as it was when originally set in the <xsl:variable name="layout" select="#template"/> statement.
Working: In preceding-sibling::*[#template = 'one'], #template varies per the #template attribute value of the varying preceding-sibling context nodes.
*[(#template = 'one')]
Above means: count all nodes where attribute template equals the text one.
*[($layout = 'one')]
Above means: count all nodes where variable layout equals the text one.
I think with the question you raised $layout is not filled with the text one, but it does a xsl:call-template. Maybe something is going wrong here?
Besides that if you don't want to count all nodes but only the chapter nodes. Do this:
chapter[($layout = 'one')]
chapter[(#template = 'one')]

XSLT Date Comparisons

<xsl:variable name="date1" select="2011-10-05"/>
<xsl:variable name="date2" select="2011-10-05"/>
<xsl:variable name="date3" select="2011-10-06"/>
<xsl:if test="$date2 = $date1 or $date2 < $date1">
..do something
</xsl:if>
<xsl:if test="$date3 = $date1 or $date3 > $date1">
.. do something
</xsl:if>
Both should evaluate true, but the second if doesn't. For the life of me I can't comprehended why!
In the actual transform the dates themselves are being drawn from an XML document but debugging through VS2010 i can see the values are as above.
Must be something fairly fundamental i'm doing wrong - any help would be brilliant!
I tried this in Oxygen/XML... select="2011-10-05 is being interpreted as an arithmetic expression, giving the value 1996 (2011 minus 10 minus 5) and "2011-10-06" is intrepreted as 1995.
What you want is
<xsl:variable name="date1" select="'2011-10-05'"/>
<xsl:variable name="date2" select="'2011-10-05'"/>
<xsl:variable name="date3" select="'2011-10-06'"/>
Note the extra single quotes.
From the XSLT 1.0 Specification:
If the variable-binding element has a select attribute, then the value
of the attribute must be an expression and the value of the variable
is the object that results from evaluating the expression.

Need to remove Note: from the start of a string using XSLT

I have been tasked with styling XML and so far nearly all of the tags I have been given are either p or ph which just display the contents of the tag on screen and I can style as required
eg:
<p outputclass="LC AStatProv">Council Regulation (EC) No 2201/2003 of 27 November 2003 Concerning Jurisdiction and the Recognition and Enforcement of Judgments in Matrimonial Matters and in Matters of Parental Responsibility, repealing Regulation (EC) No 1347/2000 (Brussels II Revised) (2003) OJ L 338/1, Art 20</p>
will display as:
Council Regulation (EC) No 2201/2003 of 27 November 2003 Concerning Jurisdiction and the Recognition and Enforcement of Judgments in Matrimonial Matters and in Matters of Parental Responsibility, repealing Regulation (EC) No 1347/2000 (Brussels II Revised) (2003) OJ L 338/1, Art 20
Today I have noticed that a new note tag has been used and this is causing "Note: " to be prepended to the beginning of each string eg:
<p outputclass="LC ACourt"><note outputclass="CaseSearchCourt">Court of Appeal</note></p>
will display as:
Note: Re A (Abduction: Interim Directions: Accommodation by Local Authority) [2010] EWCA Civ 586 [2011] 1 FLR 1
The FO produced for this is:
<fo:block><fo:inline font-weight="bold" border-right-width="0pt" border-left-width="0pt">Note: </fo:inline> Court of Appeal</fo:block>
I have tried the following code gleaned from elsewhere on this site but it didn't remove the string I wanted:
<xsl:template match="note">
<note>
<xsl:if test="contains(., 'Note:')">
<xsl:call-template name="remove">
<xsl:with-param name="value" select="."/>
</xsl:call-template>
</xsl:if>
</note>
</xsl:template>
<xsl:template name="remove">
<xsl:param name="value"/>
<xsl:value-of select="concat(substring-before($value, 'Note:'), substring-after($value, 'Note:'))"/>
</xsl:template>
I have tried to see where XSLT gets the "Note: " from but can't find it anywhere so my next thought is to try and pattern match the string and remove "Note: " from the beginning of the string. Is this a good way to go about this and how would I do this?
thanks.
EDIT: Just to summarise my rambling and confusing question.
Where it renders:
Note: Re A (Abduction: Interim Directions: Accommodation by Local Authority) [2010] EWCA Civ 586 [2011] 1 FLR 1
I just want it to render:
Re A (Abduction: Interim Directions: Accommodation by Local Authority) [2010] EWCA Civ 586 [2011] 1 FLR 1
EDIT 2 and the answer
My initial investigations were based upon grepping for Note: which wasn't being found. I have though found the following:
<xsl:template match="*[contains(#class,' topic/note ')]">
and then commented out the following lines:
<!--<xsl:text>Note</xsl:text>-->
</xsl:otherwise>
</xsl:choose>
<!--<xsl:text>: </xsl:text>-->
</fo:inline>
<xsl:text> </xsl:text>
<xsl:apply-templates/>
And I have got rid of the "Note: ".
EDIT 3:
This didn't actually work as it created an opening block but didn't close it so I ended up removing the entire <xsl:template match="*[contains(#class,' topic/note ')]"> as we have no need for any type of notes in our system
This didn't actually work as it created an opening block but didn't close it so I ended up removing the entire <xsl:template match="*[contains(#class,' topic/note ')]"> as we have no need for any type of notes in our system

XSLT line counter - is it that hard?

I have cheated every time I've needed to do a line count in XSLT by using JScript, but in this case I can't do that. I simply want to write out a line counter throughout an output file. This basic example has a simple solution:
<xsl:for-each select="Records/Record">
<xsl:value-of select="position()"/>
</xsl:for-each>
Output would be:
1
2
3
4
etc...
But what if the structure is more complex with nested foreach's :
<xsl:for-each select="Records/Record">
<xsl:value-of select="position()"/>
<xsl:for-each select="Records/Record">
<xsl:value-of select="position()"/>
</xsl:for-each>
</xsl:for-each>
Here, the inner foreach would just reset the counter (so you get 1, 1, 2, 3, 2, 1, 2, 3, 1, 2 etc). Does anyone know how I can output the position in the file (ie. a line count)?
While it is quite impossible to mark the line numbers for the serialization of an XML document (because this serialization per se is ambiguous), it is perfectly possible, and easy, to number the lines of regular text.
This transformation:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text"/>
<xsl:template match="/">
<xsl:call-template name="numberLines"/>
</xsl:template>
<xsl:template name="numberLines">
<xsl:param name="pLastLineNum" select="0"/>
<xsl:param name="pText" select="."/>
<xsl:if test="string-length($pText)">
<xsl:value-of select="concat($pLastLineNum+1, ' ')"/>
<xsl:value-of select="substring-before($pText, '
')"/>
<xsl:text>
</xsl:text>
<xsl:call-template name="numberLines">
<xsl:with-param name="pLastLineNum"
select="$pLastLineNum+1"/>
<xsl:with-param name="pText"
select="substring-after($pText, '
')"/>
</xsl:call-template>
</xsl:if>
</xsl:template>
</xsl:stylesheet>
when applied on this XML document:
<t>The biggest airlines are imposing "peak travel surcharges"
this summer. In other words, they're going to raise fees
without admitting they're raising fees: Hey, it's not a $30
price hike. It's a surcharge! This comes on the heels of
checked-baggage fees, blanket fees, extra fees for window
and aisle seats, and "snack packs" priced at exorbitant
markups. Hotels in Las Vegas and elsewhere, meanwhile, are
imposing "resort fees" for the use of facilities (in other
words, raising room rates without admitting they're
raising room rates). The chiseling dishonesty of these
tactics rankles, and every one feels like another nail in
the coffin of travel as something liberating and
pleasurable.
</t>
produces the desired line-numbering:
1 The biggest airlines are imposing "peak travel surcharges"
2 this summer. In other words, they're going to raise fees
3 without admitting they're raising fees: Hey, it's not a $30
4 price hike. It's a surcharge! This comes on the heels of
5 checked-baggage fees, blanket fees, extra fees for window
6 and aisle seats, and "snack packs" priced at exorbitant
7 markups. Hotels in Las Vegas and elsewhere, meanwhile, are
8 imposing "resort fees" for the use of facilities (in other
9 words, raising room rates without admitting they're
10 raising room rates). The chiseling dishonesty of these
11 tactics rankles, and every one feels like another nail in
12 the coffin of travel as something liberating and
13 pleasurable.
A line in an XML file is not really the same as an element. In your first example you don't really count the lines - but the number of elements.
An XML file could look like this:
<cheeseCollection>
<cheese country="Cyprus">Gbejna</cheese><cheese>Liptauer</cheese><cheese>Anari</cheese>
</cheeseCollection>
Or the exact same XML file can look like this:
<cheeseCollection>
<cheese
country="Cyprus">Gbejna</cheese>
<cheese>Liptauer</cheese>
<cheese>Anari</cheese>
</cheeseCollection>
which the XSLT will interpet exactly the same - it will not really bother with the line breaks.
Therefore it's hard to show line numbers in the way you want using XSLT - it's not really meant for for that kind of parsing.
Someone correct me if I'm wrong, but I'd say you would need Javascript or some other scripting language to do what you want.
Thanks for the responses guys - yup you're totally correct, some external function is the only way to get this behaviour in XSLT. For those searching, this is how I did this when using a compiled transform in .Net 3.5:
Create a helper class for your function(s)
/// <summary>
/// Provides functional support to XSLT
/// </summary>
public class XslHelper
{
/// <summary>
/// Initialise the line counter value to 1
/// </summary>
Int32 counter = 1;
/// <summary>
/// Increment and return the line count
/// </summary>
/// <returns></returns>
public Int32 IncrementCount()
{
return counter++;
}
}
Add an instance to an args list for XSLT
XslCompiledTransform xslt = new XslCompiledTransform();
xslt.Load(XmlReader.Create(s));
XsltArgumentList xslArg = new XsltArgumentList();
XslHelper helper = new XslHelper();
xslArg.AddExtensionObject("urn:helper", helper);
xslt.Transform(xd.CreateReader(), xslArg, writer);
Use it in you XSLT
Put this in the stylesheet declaration element:
xmlns:helper="urn:helper"
Then use like so:
<xsl:value-of select="helper:IncrementCount()" />
Generally, position() is referring to the number of the current node relative to the entire batch of nodes that is being processed currently.
With your "nested for-each" example, consecutive numbering can easily be achieved when you stop nesting for-each constructs and just select all desired elements at once.
With this XML:
<a><b><c/><c/></b><b><c/></b></a>
a loop construct like this
<xsl:for-each "a/b">
<xsl:value-of select="position()" />
<xsl:for-each "c">
<xsl:value-of select="position()" />
</xsl:for-each>
</xsl:for-each>
will result in
11221
bccbc // referred-to nodes
but you could simply do this instead:
<xsl:for-each "a/b/c">
<xsl:value-of select="position()" />
</xsl:for-each>
and you would get
123
ccc // referred-to nodes