且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

XPATH:选择 xml 文件的子集

更新时间:2022-11-26 18:04:04

与其选择您确实想要的元素,不如尝试排除你不想要的元素.

Rather than selecting the element that you do want, try excluding the elements that you don't want.

如果您只是使用 XPATH,这将选择除 book 元素之外的所有元素,@id 不等于1(即 ).

If you are just using XPATH, this will select all of the elements except for the book elements who's @id is not equal to 1 (i.e. <booklist><book id="1" /></booklist>).

//*[not(self::book[@id!='1'])]

如果您需要 XSLT 解决方案,此样式表有一个空模板,它匹配所有没有 @id= 的 元素1",防止它们被复制到输出中.

If you want an XSLT solution, this stylesheet has an empty template that matches all of the <book> elements that do not have @id="1", which prevents them from being copied into the output.

其他所有内容(文档节点 )都将匹配身份模板,然后向前复制.>

Everything else (document node <booklist> and <book id="1">) will match the identity template, which copies forward.

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

    <!--Empty template to prevent book elements
        that do not have @id="1" from being
        copied into the output -->
    <xsl:template match="book[@id!='1']" />

    <!--identity template to copy all nodes and attributes to output -->
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

</xsl:stylesheet>