Is it possible for me to have a conditional in XSLT such that I find and replace only the FIRST tag of a particular tag name?
For example, I have an XML file with many <title> tags. I would like to replace the first of these tags with <PageTitle>. The rest should be left alone. How would I do this in my transform? What I currently have is this:
<xsl:template match="title">
<PageTitle>
<xsl:apply-templates />
</PageTitle>
</xsl:template>
which finds all <title> tags and replaces them with <PageTitle>. Any help would be greatly appreciated!
The first
titleelement in the document is selected by:(//title)[1]Many people mistakenly think that
//title[1]selects the firsttitlein the document and this is a frequently committed error.//title[1]selects everytitleelement that is the firsttitlechild of its parent — not what is wanted here.Using this, the following transformation produces the required output:
When applied on this XML document:
the wanted result is produced:
Do note how we use the well-known Kaysian method of set intersection in XPath 1.0:
If there are two nodesets
$ns1and$ns2, the following expression selects every node which belongs to both$ns1and$ns2:$ns1[count(.|$ns2) = count($ns2)]In the specific case when both node-sets contain only one node, and one of them is the current node, the following expression evaluates to
true()exactly when the two nodes are identical:count(.|$ns2) = 1A variation of this is used in the match pattern of the template that overrides the identity rule:
title[count(.|((//title)[1])) = 1]matches only the first
titleelement in the document.