Reputation: 2473
I am using a "xsl:for-each" to iterate over each element with name content and attribute that contains the text "period". When attempting to take out one date per each "xsl:for-each" iteration, it returns 2 values.
The matching of text "period" must be done like this due to the input data might change and it is unknown how many elements with id containing ="period", that would appear in the data.
I would like to keep the xpath search critera in the "xsl:for-each" syntax, because I am using the template to point out root.
When I try to subset the dates using date[1]
it still return both dates.
Same code as in above fiddle:
Data:
<?xml version="1.0" encoding="utf-8" ?>
<section>
<content id="period1">
<date>2021-01-01</date>
</content>
<content id="period2">
<date>2020-01-01</date>
</content>
</section>
XSL:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="3.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
exclude-result-prefixes="#all"
>
<xsl:mode on-no-match="shallow-copy"/>
<xsl:output method="html" indent="yes" html-version="5"/>
<xsl:template match="/section">
<xsl:for-each select="//content/@*[contains(., 'period')]">
<date>
<!--<xsl:value-of select="."/>-->
<!--<xsl:value-of select="//date[1]"/>-->
<xsl:value-of select="//content/date"/>
</date>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
Result:
<!DOCTYPE HTML>
<date>2021-01-01 2020-01-01</date>
<date>2021-01-01 2020-01-01</date>
Wanted result:
<!DOCTYPE HTML>
<date>2021-01-01</date>
<date>2020-01-01</date>
Upvotes: 0
Views: 262
Reputation: 167436
Use relative paths
<xsl:for-each select="content[@*[contains(., 'period')]]">
<date>
<!--<xsl:value-of select="."/>-->
<!--<xsl:value-of select="//date[1]"/>-->
<xsl:value-of select="date"/>
</date>
</xsl:for-each>
Upvotes: 2