I am using Googles XML custom site search (Google XML sitesearch) and I am using XSLT in .NET to transform the results to HTML. I have 开发者_如何学Pythona few question regarding XSLT.
1) Google will return something similar to the following
<GSP VER="3.2">
<PARAM name="start" value="0" />
<PARAM name="num" value="10" />
<RES>
<R>
<PageMap>
<DataObject>
<Attribute name="Rating" value="4.5" />
<Attribute name="RatingCount" value="743" />
</DataObject>
</PageMap>
</R>
</RES>
</GSP>
I am wondering the following:
How would I get the value of one of the PARAM (i.e. Start or num)? And how would I get the value of one of the DataObject's Attributes?
Any help much appreciated.
Thanks
Never use //
when the schema is known.
To get start value use:
/GSP/PARAM[@name='start']/@value
To get num parameter:
/GSP/PARAM[@name='num']/@value
To get rating:
/GSP/RES/R/PageMap/DataObject/Attribute[@name='Rating']/@value
Using XPath you could refer to these values like this:
/GSP/PARAM[@name='num']/@value
For DataObject Attributes it would be
//DataObject/Attribute[@name='Rating']/@value
However you need to clarify in which context you need to get these values as expressions might me shorter in most cases (I used full path).
I suggest to use keys in case if params in this sample needs to be accessed by names from various contexts. Using keys will also protect your sources from repeating xpath again and again.
<!-- Key declaration -->
<xsl:key name="gsp-param" match="/GSP/PARAM/@value" use="../@name"/>
<xsl:template name="some-template">
<!-- Get key value in unknown context -->
<xsl:value-of select="key('gsp-param', 'num')"/>
</xsl:template>
精彩评论