XSLT:带有子节点的文本上的分析字符串 [英] XSLT: analyze-string on text with children nodes
问题描述
我正在尝试对可能包含子节点的元素使用分析字符串.这是源文件的片段:<年>1975 音乐</年><年>1985<genre>摇滚</genre>音乐</年><年>2005 音乐</年>
I am trying to use analyze-string on elements that possibly contain children nodes. Here is a snippet of a source file:
<year>
1975 music
</year>
<year>
1985<genre>rock</genre>music
</year>
<year>
2005 music
</year>
这是我想要的:
<year>
70's music
</year>
<year>
80's<genre>rock</genre> music
</year>
以下代码正确匹配了 3 种情况,但我缺少一些东西来复制年份元素下的文本和可能的子节点:
The following code correctly matches the 3 cases, but I am missing something to copy both the text and the possible children nodes under the year element:
<xsl:template match="year">
<xsl:variable name="item" select="."/>
<xsl:analyze-string select="." regex="19(\d)\d">
<xsl:matching-substring>
<xsl:variable name="decade">
<xsl:value-of select="concat(regex-group(1),'0''s')"/>
</xsl:variable>
<year>
<xsl:value-of select="concat($decade,regex-group(2))"/>
<genre><xsl:value-of select="$item/genre"/>
</genre>
</year>
</xsl:matching-substring>
<xsl:non-matching-substring> </xsl:non-matching-substring>
</xsl:analyze-string>
</xsl:template>
这是我得到的:
<year>70's<genre/></year>
<year>80's<genre>rock</genre></year>
在此先感谢您的帮助!
推荐答案
似乎足以匹配年份模式的文本子项:
It seems to suffice to match on the text child for the year pattern:
<xsl:template match="year[not(matches(., $pattern))]"/>
<xsl:template match="year/text()[matches(., $pattern)]">
<xsl:value-of select="replace(., $pattern, '$10''s')"/>
</xsl:template>
这给了
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
exclude-result-prefixes="#all"
version="3.0">
<xsl:mode on-no-match="shallow-copy"/>
<xsl:param name="pattern" as="xs:string">19(\d)\d</xsl:param>
<xsl:output method="xml" indent="yes"/>
<xsl:template match="year[not(matches(., $pattern))]"/>
<xsl:template match="year/text()[matches(., $pattern)]">
<xsl:value-of select="replace(., $pattern, '$10''s')"/>
</xsl:template>
</xsl:stylesheet>
https://xsltfiddle.liberty-development.net/gWmuiJV 给出了结果
<root>
<year>
70's music
</year>
<year>
80's<genre>rock</genre>music
</year>
</root>
对于 XSLT 2 兼容解决方案,您需要详细说明用作身份转换模板的 xsl:mode
声明,例如 http://xsltransform.hikmatu.com/jyH9rLQ.
For an XSLT 2 compatible solution you would need to spell out the xsl:mode
declaration used as the identity transformation template, example for that at http://xsltransform.hikmatu.com/jyH9rLQ.
这篇关于XSLT:带有子节点的文本上的分析字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!