首页 > 解决方案 > 通过匹配另一个节点名称来获取一个节点或通过匹配另一个节点来排除一个节点

问题描述

我有以下 XML

  <section>
            <object>
                <field name="First Source" />
                <tableSection 
                        propertyCount="1"
                        rowCount="1">
                    <tableProperty height="0"
                            width="570"
                            visible="true">
                        <property name="commit" />
                    </tableProperty>
                    <tableRow height="0"
                            width="0">
                        <tableCell value="Value First Source" />    
                    </tableRow>
                </tableSection>
            </object>
            <object>
                <field name="Another Source" />
                <tableSection 
                        propertyCount="1"
                        rowCount="1">
                    <tableProperty height="0"
                            width="570"
                            visible="true">
                        <property name="commit" />
                    </tableProperty>    
                    <tableRow height="0"
                            width="0">
                        <tableCell value="Invalid Value" />
                    </tableRow>
                </tableSection>
            </object>
        </section>

并有一个如下的xslt

<xsl:template match="tableRow">
    <xsl:variable name="rowNodePosition">
        <xsl:value-of select="position()"/>
    </xsl:variable>
    <tr allowDblCl="true"  valign="top"  height="50px">
        <td>
            <b>Row:</b>
            <xsl:value-of select="$rowNodePosition"/>
            <br/>
            <xsl:for-each select="tableCell" >

                <xsl:variable name="currPosition">
                    <xsl:value-of select="position()"/>
                </xsl:variable>                 
                <xsl:if test="@value != ''">
                    <b>
                        <xsl:value-of select="../../tableProperty[position() = $currPosition]/property/@name"/>: </b>
                    <xsl:value-of select="@value"/>
                    <br/>
                </xsl:if>
            </xsl:for-each>
        </td>
    </tr>
    <tr>
        <td colspan="4" height="15px"> </td>
    </tr>
</xsl:template>

这将获得所有的“tablRow”。但我需要排除具有字段名称='Another Source'的tableRows,即如果对象节点具有名称为“Another Source”的'field',则排除节点tableSection的tableRow

节点层次结构

标签: xmlxslttransform

解决方案


正如您所写,您希望排除每个tableRow元素,并使用具有特定值的相应字段名称。

如果要排除 XSLT 中的某些元素,一般规则是 为该元素编写一个空模板。

此元素的名称是tableRow,但要缩小匹配范围,您必须添加以下谓词:

  • 向上移动 2 个级别(到对象级别)。
  • 下降到子字段元素。
  • 下降到其名称属性。
  • 检查其内容是否为Another Source

所以添加:

<xsl:template match="tableRow[../../field/@name = 'Another Source']"/>

到您的 XSLT 脚本,以实现您想要的。

有关工作示例,请参见http://xsltransform.net/ei5PwjS


推荐阅读