简体   繁体   中英

In XSLT 1.0, how can I access attributes of a particular XML element when it is one of multiple elements with the same name?

I blame the Google Search Appliance for making me ask this question.

Here is a snippet of the XML returned by the Appliance:

<GSP VER="3.2">
<TM>0.073846</TM>
<Q>test</Q>
<PARAM name="entqr" value="0" original_value="0"/>
<PARAM name="access" value="p" original_value="p"/>
<PARAM name="output" value="xml_no_dtd" original_value="xml_no_dtd"/>
<PARAM name="sort" value="date:D:L:d1" original_value="date%3AD%3AL%3Ad1"/>
<PARAM name="ud" value="1" original_value="1"/>
<PARAM name="ie" value="UTF-8" original_value="UTF-8"/>
<PARAM name="btnG" value="Search" original_value="Search"/>
<PARAM name="client" value="default_frontend" original_value="default_frontend"/>
<PARAM name="oe" value="UTF-8" original_value="UTF-8"/>
<PARAM name="q" value="I like stuff" original_value="I like stuff"/>
...

I need to do an xsl:value-of for a specific one of those PARAM elements, conditionally based on its name. eg I need to output the @value for the PARAM element with @name="client".

Thanks!

You can declare xsl:key as a top-level element:

  <xsl:key name="param" match="PARAM" use="@name"/>

and then use key(key-name,value) function.

<xsl:value-of select="key('param','q')/@value"/>

It takes time to 'init' key but further it's much faster than selecting node[predicate] each time. So it's better to use it when you need to access PARAMs multiple times.

http://www.w3.org/TR/xslt#key

Also, knowing your tree, you can match your nodes (PARAM) more accurately.

Try using predicates on your XPath statements! try something like:

<xsl:value-of select="PARAM[@name='output']/@value"/>
<xsl:value-of select="//PARAM[@name='client']/@value" />

You didn't add the complete XML document. In case there is a default namespace involved you will have to declare a prefix that you want to use and prepend that to the element and attribute names respectively.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM