XPATH:选择 xml 文件的子集 [英] XPATH: select subset of xml file

查看:27
本文介绍了XPATH:选择 xml 文件的子集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

就我而言,我有:

<booklist>
  <book id="1">
  </book>

  <book id="2">
  </book>

  <book id="3">
  </book>

  ......

</booklist>

我怎么才能回来:

<booklist>
  <book id="1">
  </book>
</booklist>

如果我使用/booklist/book[@id=1],我只能得到

if I use /booklist/book[@id=1], I can only get

<book id="1">
</book>

但我也需要文档元素.谢谢

But I also need the document element. Thanks

推荐答案

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

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>

这篇关于XPATH:选择 xml 文件的子集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆