Selecting nodes depending on sibling node criteria using XSLT
Suppose I have XML like this:
<child_metadata>
<metadata>
<attributes>
<metadata_key value="include"/>
<metadata_value value="value1"/>
</attributes>
</metadata>
<metadata>
<attributes>
<metadata_key value="dont_include"/>
<metadata_value value="value2"/>
</attributes>
</metadata>
<开发者_JS百科metadata>
<attributes>
<metadata_key value="include"/>
<metadata_value value="value3"/>
</attributes>
</metadata>
</child_metadata>
Using XSLT (without any extensions), I want to select only those values for which the metadata_key is "include". So, for this example, I want to select value1 and value3.
How do I do this?
The XPath expression to use (for a template or in a for-each loop) would be:
//metadata_value[../metadata_key/@value='include']/@value
Since it isn't clear what you mean by "select" I cannot post a complete XSLT sample. XSLT is for transformation, not query ("selection" of data); the query is done with XPath expressions such as the one I provided you above.
For the metadata_value
node set, use
//metadata/attributes[metadata_key/@value='include']/metadata_value
add @value
to get the values themselves.
I think you want
//atributes[metadata_key/@value='include']/metadata_vale/@value
or (as Lucero post)
//metadata_value[../metadata_key/@value='include']/@value
But, depending on what you want to do, you should use keys because here is a cross-reference (metadata_key/@value
is used as the key to metadata_value/@value
). It is also good to avoid the descendant axis.
Use:
/child_metadata/metadata/attributes[metadata_key/@value='include']/metadata_value/@value
Using the //
abbreviation often has poor efficiency as this causes the whole (sub) tree to be traversed.
精彩评论