5

如何选择具有唯一 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>
4

5 回答 5

4

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

//book[@id=3]

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

于 2012-06-27T05:53:42.527 回答
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>

... 将您的示例输入文档转换为指定的示例输出文档

于 2012-06-27T06:06:39.937 回答
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].

于 2016-08-12T22:57:04.867 回答
0

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

<xsl:copy-of select="/*/library/book[@id=3]"/>
于 2012-06-27T06:03:59.903 回答
-2

看看 SimpleXML xpath

xpath simpleXML

于 2012-06-27T05:51:24.477 回答