[英]Removing elements from nodes or nodes from xml when attribute and text content match using xslt 2.0
[英]How to parse text nodes in xml using XSLT 2.0 functions
假设我有这个临时文件:
<xsl:variable name="var">
<root>
<sentence>Hello world</sentence>
<sentence>Foo foo</sentence>
</root>
</xsl:variable>
我正在使用分析字符串来查找“世界”字符串,并用名为<match>
元素包装
<xsl:function name="my:parse">
<xsl:param name="input"/>
<xsl:analyze-string select="$input" regex="world">
<xsl:matching-substring>
<match><xsl:copy-of select="."/></match>
</xsl:matching-substring>
<xsl:non-matching-substring>
<xsl:copy-of select="."/>
</xsl:non-matching-substring>
</xsl:analyze-string>
</xsl:function>
该函数将返回:
Hello <match>world</match>Foo foo
自然,我想要此输出:
<root>
<sentence>Hello <match>world</match></sentence>
<sentence>Foo foo</sentence>
</root>
不过,我知道为什么我的函数会这样做,但是我无法弄清楚如何复制元素并将元素注入新内容。 我知道上下文项目存在问题,但是我尝试了许多其他方法,但对我来说却无济于事。
另一方面,使用匹配//text()
模板也可以。 但是要求是使用函数(因为我正在进行多相转换并且我想使用代表每个步骤的函数)。 我想知道是否有解决此问题的方法? 我缺少基本的东西吗?
如果您一次只需要在一个文本节点上进行匹配,那么执行此操作的方法是使用模板规则,元素的标识模板以及为您的analyzer-string做模板的模板进行树的递归下降文本节点。 使用一种模式将此模式与其他处理逻辑分开,然后从函数中调用apply-templates来指定此模式,因此模板的使用完全隐藏在该函数的实现中。
这是我对Michael Kay(+1)建议的解释的一个示例...
XSLT 2.0
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:my="my" exclude-result-prefixes="my">
<xsl:output indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="@*|node()" mode="#all" priority="-1">
<xsl:copy>
<xsl:apply-templates select="@*|node()" mode="#current"/>
</xsl:copy>
</xsl:template>
<xsl:variable name="var">
<root>
<sentence>Hello world</sentence>
<sentence>Foo foo</sentence>
</root>
</xsl:variable>
<xsl:function name="my:parse">
<xsl:param name="input"/>
<xsl:apply-templates select="$input" mode="markup-step"/>
</xsl:function>
<xsl:template match="/*">
<xsl:copy-of select="my:parse($var)"/>
</xsl:template>
<xsl:template match="text()" mode="markup-step">
<xsl:analyze-string select="." regex="world">
<xsl:matching-substring>
<match><xsl:copy-of select="."/></match>
</xsl:matching-substring>
<xsl:non-matching-substring>
<xsl:copy-of select="."/>
</xsl:non-matching-substring>
</xsl:analyze-string>
</xsl:template>
</xsl:stylesheet>
输出 (使用任何格式正确的XML输入)
<root>
<sentence>Hello <match>world</match>
</sentence>
<sentence>Foo foo</sentence>
</root>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.