问题
Take the following XML sample:
<Meeting BookmarkId="0" PageBreak="0" NumberClasses="1" SpecialEvent="1">
<Date ThisWeek="W20200406" NextWeek="W20200413">April 6-12</Date>
<SpecialEvent>
<Event>Memorial</Event>
<Location>Address goes here</Location>
<Date Day="7" DayShort="Tue" DayFull="Tuesday" Month="4" MonthShort="Apr" MonthFull="April" Year="2020">07/04/2020</Date>
</SpecialEvent>
</Meeting>
Bear in mind that this XML content is automatically created for about 50 languages so the locales used for the days of the week differ obviously.
Is it possible using XSLT-1 to programatically determine if the date is midweek or weekend (irrespective of the locale of the data)?
If needs must I will change the logic of my applicate that creates the XML to include a new boolean attribute stating if it is midweek or weekend. But I wanted to know if it was easy to text for with a XSL if
condition.
回答1:
Try 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"/>
<!-- identity transform -->
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="SpecialEvent/Date">
<xsl:copy>
<xsl:copy-of select="@*"/>
<xsl:variable name="day-of-week">
<xsl:call-template name="day-of-week">
<xsl:with-param name="year" select="@Year"/>
<xsl:with-param name="month" select="@Month"/>
<xsl:with-param name="day" select="@Day"/>
</xsl:call-template>
</xsl:variable>
<xsl:attribute name="Weekend">
<xsl:value-of select="$day-of-week < 2"/>
</xsl:attribute>
<xsl:apply-templates/>
</xsl:copy>
</xsl:template>
<xsl:template name="day-of-week">
<!-- http://en.wikipedia.org/wiki/Zeller%27s_congruence -->
<xsl:param name="year" />
<xsl:param name="month"/>
<xsl:param name="day"/>
<!-- m is the month (3 = March, 4 = April, 5 = May, ..., 14 = February) -->
<xsl:variable name="a" select="$month < 3"/>
<xsl:variable name="m" select="$month + 12*$a"/>
<xsl:variable name="y" select="$year - $a"/>
<xsl:variable name="K" select="$y mod 100"/>
<xsl:variable name="J" select="floor($y div 100)"/>
<!-- h is the day of the week (0 = Saturday, 1 = Sunday, 2 = Monday, ..., 6 = Friday) -->
<xsl:variable name="h" select="($day + floor(13*($m + 1) div 5) + $K + floor($K div 4) + floor($J div 4) - 2*$J) mod 7"/>
<xsl:value-of select="$h"/>
</xsl:template>
</xsl:stylesheet>
来源:https://stackoverflow.com/questions/60129315/testing-xml-data-for-being-midweek-or-weekend-with-xslt-1