请建议如何在 tokenize 中获取前面的文本。在此示例中,将应用基于前面文本的 Web 属性。例如,如果“SKY1996”类型文本前面带有字符串“Moon”,则属性值为“Moon”,否则为“Sun”。
XML:
<article>
<text1>The solar eclipse Sun: SKY1996 is happenned in 1996</text1>
<text2>The moon eclipse Moon: SKY1997 is happenned in 1997</text2>
</article>
XSLT 2.0:
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="@*|node()">
<xsl:copy><xsl:apply-templates select="@*|node()"/></xsl:copy>
</xsl:template>
<xsl:template match="text1/text()|text2/text()">
<xsl:for-each select="tokenize(., ' ')">
<xsl:variable name="varPrecededText"><xsl:value-of select=".[preceding-sibling::node()[1]]"/></xsl:variable><!--Within tokenize, preceded text value --><!--Requesting suggestion to get this -->
<xsl:choose>
<xsl:when test="matches(., '^([S][K][Y])\d{4}$')">
<xsl:element name="web">
<xsl:attribute name="href">
<xsl:choose>
<xsl:when test="contains($varPrecededText, 'Moon')">
<xsl:text>MoonEclipse:</xsl:text>
</xsl:when>
<xsl:otherwise><xsl:text>SunEclipse:</xsl:text></xsl:otherwise>
</xsl:choose>
<xsl:value-of select="."/>
</xsl:attribute>
<xsl:value-of select="."/>
</xsl:element><xsl:if test="not(position()=last())"><xsl:text> </xsl:text></xsl:if>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="."/>
<xsl:if test="not(position()=last())"><xsl:text> </xsl:text></xsl:if>
</xsl:otherwise>
</xsl:choose>
</xsl:for-each>
</xsl:template>
所需结果:
<article>
<text1>The solar eclipse Sun: <web href="SunEclipse:SKY1996">SKY1996</web> is happenned in 1996</text1>
<text2>The moon eclipse Moon: <web href="MoonEclipse:SKY1997">SKY1997</web> is happenned in 1997</text2>
</article>
最佳答案
我会简单地使用分析字符串:
<xsl:template match="text1/text()|text2/text()">
<xsl:analyze-string select="." regex="((\w+):)\s+([S][K][Y]\d{{4}})">
<xsl:matching-substring>
<web href="{regex-group(2)}Eclipse:{regex-group(3)}">
<xsl:value-of select="regex-group(3)"/>
</web>
</xsl:matching-substring>
<xsl:non-matching-substring>
<xsl:value-of select="."/>
</xsl:non-matching-substring>
</xsl:analyze-string>
</xsl:template>
((\w+):)\s+([S][K][Y]\d{{4}})
捕获 Sun: SKY1996
和 Moon:第 2 组中的 SKY1997
、Sun
和 Moon
,第 2 组中的 SKY1996
和 SKY1997
3. 这些匹配在xsl:matching-substring中处理,以将它们替换为所需的结构。不匹配的内容保持原样。
关于xml - 在xsl tokenize中,如何获取前面的文本值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38700076/