2012-06-27 47 views
4

唯一的ID选择节点如何选择具有唯一ID的特定节点,并返回整个节点为XML。使用XSLT

<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

这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> 

...将改变你样本输入文档到指定的示例输出文档

+0

如果id是当前元素的属性,该如何实现? – Hunsu

+0

让你的问题在#1一个单独的问题。 –

+0

这里http://stackoverflow.com/questions/28673341/how-to-select-element-by-attribute-with-xslt – Hunsu

2

如果你指的是XPath(因为你是在文档中搜索,没有转换它),这将是:

//book[@id=3] 

当然,这取决于你的语言,有可能使这个搜索更简单的库。

+0

又在想,也许'//书[@ ID = '3']'是比较合适的。我不确定细节,但可以在更多情况下工作(例如,当ID不是数字时) – Kobi

1

在XSLT使用xsl:copy-of插入一个选择的节点设置为输出结果树:

<xsl:copy-of select="/*/library/book[@id=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%的整体加速在我的情况。测量对//book[@id = $id-to-look-up]