XSLT 匹配文本节点与另一个元素的相同文本节点不匹​​配的元素

XSLT match elements with text nodes that do not match the same text node from another element

在此示例中 XML 我想匹配 app 元素,其中 indexInfo 元素中的文本与 z_app 元素中的相同文本不匹配同名。

由于 appname2z_appname2 中的 indexInfo 元素都匹配,所以我不想包含这些。在这种情况下,我只想返回应用程序元素 appname1z_appname1,因为它们的 indexInfo 内容不同。

我正在寻找可用于 XSLT 模板的匹配表达式。

<root>
    <app name="appname1">
      <indexInfo>
This is the text for the indexes
      </indexInfo>
    </app>
    
    <app name="z_appname1">
      <indexInfo>
This is the text for the indexes
But slightly different
      </indexInfo>
    </app>
    
    <app name="appname2">
      <indexInfo>
This is the text for the indexes
      </indexInfo>
    </app>
    
    <app name="z_appname2">
      <indexInfo>
This is the text for the indexes
      </indexInfo>
    </app>
</root>

期望的输出:

<root>
    <app name="appname1">
      <indexInfo>
This is the text for the indexes
      </indexInfo>
    </app>

    <app name="z_appname1">
      <indexInfo>
This is the text for the indexes
But slightly different
      </indexInfo>
    </app>
</root>

您可以使用 xsl:key 创建匹配所有 app 元素的映射,使用“appname”之后的 @name 的值和 [=14= 的值] 作为查找键。

然后,在模板匹配表达式中,应用谓词匹配任何 app,其中通过该键选择的项目有多个项目,使用空模板排除该匹配 app从输出:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    
    <xsl:key name="app" match="app" use="concat(substring-after(@name, 'appname'), '|', indexInfo)"/>
    
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>
    
    <xsl:template match="app[key('app', concat(substring-after(@name, 'appname'), '|', indexInfo))[2]]"/>
    
</xsl:stylesheet>

我会这样做:

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"/>
<xsl:strip-space elements="*"/>

<xsl:key name="app-by-name" match="app" use="@name" />

<xsl:template match="/root">
    <xsl:copy>
        <xsl:for-each select="app[starts-with(@name, 'z_')]">
            <xsl:variable name="peer" select="key('app-by-name', substring-after(@name, 'z_'))" />
            <xsl:if test="indexInfo != $peer/indexInfo">
                <xsl:copy-of select=". | $peer"/>
            </xsl:if>
        </xsl:for-each>
    </xsl:copy>
</xsl:template>
    
</xsl:stylesheet>