Reputation: 166
I am trying to get a set of nodes in an XML file, by using the match attribute the following way -
<xsl:template match="//title" name="split">
and it doesn't seem to work.
this is the XML file I am trying to work with (taken from https://www.w3schools.com/xml/xpath_syntax.asp )
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="c.xsl"?>
<bookstore>
<book>
<title lang="en">Harry Potter</title>
<price>29.99</price>
</book>
<book>
<title lang="en">Learning XML</title>
<price>39.95</price>
</book>
</bookstore>
this is the xsl file I am trying to run
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:template match="//title" name="split">
<xsl:value-of select=".">
</xsl:value-of>
</xsl:template>
</xsl:stylesheet>
the desired output is : Harry Potter Learning XML
Upvotes: 1
Views: 426
Reputation: 461
You have a template matching the title correctly, but you don't have anything catching and ignoring everything else, so all the text content is going to be included.
Throw in a match-all template which just re-applies the stylesheet on everything else. Note if you do it this way you don't need the wildcard //title
match and can just match on the element name.
XSL
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes" />
<xsl:template match="title" name="split">
<xsl:value-of select="concat(., ' ')" />
</xsl:template>
<xsl:template match="@*|node()">
<xsl:apply-templates select="@*|node()" />
</xsl:template>
</xsl:stylesheet>
Output
Harry Potter Learning XML
Upvotes: 3
Reputation: 13006
use this. added space in between the concatenated values, feel free to modify
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:template name="concatvalues" match="bookstore">
<xsl:variable name="concatenatedValue">
<xsl:for-each select="book/title">
<xsl:if test="position() != last()">
<xsl:value-of select="concat(./text(), ' ')"/>
</xsl:if>
<xsl:if test="position() = last()">
<xsl:value-of select="./text()"/>
</xsl:if>
</xsl:for-each>
</xsl:variable>
<xsl:value-of select="$concatenatedValue"/>
</xsl:template>
</xsl:stylesheet>
Upvotes: 1