使用XSLT选择具有唯一ID的节点

6

如何选择具有唯一标识符的特定节点,并将整个节点作为xml返回。

<xml>
<library>
<book id='1'>
<title>firstTitle</title>
<author>firstAuthor</author>
</book>
<book id='2'>
<title>secondTitle</title>
<author>secondAuthor</author>
</book>
<book id='3'>
<title>thirdTitle</title>
<author>thirdAuthor</author>
</book>
</library>
</xml>

在这种情况下,我想返回id为“3”的书籍,因此它将类似于以下内容:

<book id='3'>
<title>thirdTitle</title>
<author>thirdAuthor</author>
</book>
5个回答

5
如果你指的是XPath(因为你在搜索文档,而不是转换它),那么应该是:
//book[@id=3]

当然,根据您使用的语言,可能会有一个库使这个搜索过程变得更加简单。

重新思考一下,也许 //book[@id='3'] 更合适。我不确定细节,但在更多情况下都可以工作(例如,当ID不是数字时)。 - Kobi

4
这个XSLT 1.0样式表...
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>

<xsl:template match="/">
  <xsl:apply-templates select="*/*/book[@id='3']" />
</xsl:template>

<xsl:template match="@*|node()">
  <xsl:copy>
   <xsl:apply-templates select="@*|node()" />
  </xsl:copy>
</xsl:template>

</xsl:stylesheet>

...将把您的样例输入文档转换为所述的样例输出文档。


如果id是当前元素的属性,如何实现这个? - Hunsu
在Stackoverflow中,请将你的问题作为一个独立的问题。 - Sean B. Durkin
如何使用XSLT按属性选择元素 - Hunsu

3
最高效和易读的方法是通过 key 进行操作:
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

    <!-- To match your expectation and input (neither had <?xml?> -->
    <xsl:output method="xml" omit-xml-declaration="yes" />

    <!-- Create a lookup for books -->
    <!-- (match could be more specific as well if you want: "/xml/library/book") -->
    <xsl:key name="books" match="book" use="@id" />

    <xsl:template match="/">
        <!-- Lookup by key created above. -->
        <xsl:copy-of select="key('books', 3)" />
        <!-- You can use it anywhere where you would use a "//book[@id='3']" -->
    </xsl:template>

</xsl:stylesheet>

* 对于2142个条目和121个查找,它可以节省500毫秒的时间,在我的情况下实现了33%的整体加速。与//book[@id = $id-to-look-up]比较测量。

0
在XSLT中,您可以使用xsl:copy-of将所选节点集插入输出结果树中:
<xsl:copy-of select="/*/library/book[@id=3]"/>

-2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接