如果条件为真,如何获取父节点及其所有子节点

How to get parent node and all it's child node if a condition is true

我得到了以下XML

<?xml version="1.0" encoding="utf-8"?>
<Students>
    <Student>
        <StdId value="1"/>
        <Name>a</Name>
        <Courses>
            <Course value="c1"/>
            <Course value="c2"/>
            <Course value="c3"/>
        </Courses>
    </Student>
    <Student>
        <StdId value="2" InActive="True"/>
        <Name>b</Name>
        <Courses>
            <Course value="c1"/>
            <Course value="c4"/>
            <Course value="c6"/>
        </Courses>
    </Student>
</Students>

我的 XSLT 代码是

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
    <xsl:output method="xml" indent="yes"/>
    <xsl:strip-space elements="*"/>
    <xsl:template match="/">
        <xsl:result-document method="xml" href="file:///C:/Student_details.xml">
            <xsl:for-each select="Students/Student">
                <xsl:if test="(StdId[@InActive != 'True'])">
                    <xsl:copy-of select="Student"/>
                </xsl:if>
            </xsl:for-each>
        </xsl:result-document>
    </xsl:template>
</xsl:stylesheet>

我想获取 Student 元素及其子节点,而不是 StdId InActive="True"。我的代码没有复制任何学生元素。

  1. 如果属性根本不存在,则找不到该节点。

    <StdId value="1" InActive="False"/>

会被发现。

您可以使用

 <xsl:if test="(StdId[@InActive!= 'True'] or StdId[not(@InActive)])">

为了改变 select 属性不存在的节点。

  1. <xsl:copy-of select="Student" /> 不起作用。 您可以使用
    <xsl:copy-of select="node()" /> 到 select 当前节点(这只是 Student 节点的内容),或者 <xsl:copy-of select="../Student" />,为了也得到 <Student> ... </Student> 标签。

您可以将 for-each select 中的 XPath 更改为仅遍历那些没有 InActive = "True" 属性的对象,如下所示:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
    <xsl:output method="xml" indent="yes"/>
    <xsl:strip-space elements="*"/>
    <xsl:template match="/">
        <xsl:result-document method="xml">
            <xsl:for-each select="Students/Student[not(StdId/@InActive)]">
                    <xsl:copy-of select="."/>
            </xsl:for-each>
        </xsl:result-document>
    </xsl:template>
</xsl:stylesheet>

请注意,您的输出无效 XML,因为它没有根节点。

或者,您可以使用模板匹配,如下所示:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
    <xsl:output method="xml" indent="yes"/>
    <xsl:strip-space elements="*"/>
    <xsl:template match="Student[not(StdId/@InActive)]">
        <xsl:copy-of select="."/>
    </xsl:template>
    <xsl:template match="/">
        <xsl:result-document method="xml">
            <root>
                <xsl:apply-templates/>
            </root>
        </xsl:result-document>
    </xsl:template>
</xsl:stylesheet>

在我的第二个样式表中,我添加了一个根节点 - 这是为了我自己的本地测试,ymmv。

我还在我的第一个样式表中编辑了 XPath,因为您在评论中说过该属性只有在其值为 "True" 时才会出现。