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

时间:2012-06-27 05:43:12

标签: xml xslt

如何选择具有唯一ID的特定节点并将整个节点作为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 个答案:

答案 0 :(得分: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>

...会将您的样本输入文档转换为所述的样本输出文档

答案 1 :(得分:2)

如果您指的是XPath(因为您正在搜索文档,而不是对其进行转换),那就是:

//book[@id=3]

当然,根据您的语言,可能会有一个库使搜索更简单。

答案 2 :(得分:1)

在XSLT中,您使用xsl:copy-of将选定的节点集插入到输出结果树中:

<xsl:copy-of select="/*/library/book[@id=3]"/>

答案 3 :(得分:0)

最高效且可读的方法是通过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%。根据{{​​1}}。

衡量

答案 4 :(得分:-2)

看一下SimpleXML xpath

xpath simpleXML

相关问题