Select a node based on value of another node using an xsl predicate

8.3k views Asked by At

Similar problem to this question: XPath: select a node based on another node?

The object is to select a node based on the value of a sibling node-in this case the Pagetitle node based on the value of the Pagetype node.

xpaths:

/dsQueryResponse/Rows/Row/@Title
/dsQueryResponse/Rows/Row/@Pagetype
/dsQueryResponse/Rows/Row/@Pagetitle

This xsl isn't returning anything:

<xsl:value-of select= "/dsQueryResponse/Rows/Row[Pagetype='Parent']/@Pagetitle" />  

Sample xml:

<dsQueryResponse>
       <Rows>
            <Row>
               <Title>1</Title>
               <Pagetype>Parent</Pagetype>
               <Pagetitle>title of page</Pagetitle>
            </Row>
        </Rows>
</dsQueryResponse>  

The goal is to have the values of Pagetitle returned if they have a Pagetype value of "Parent".

3

There are 3 answers

2
Aaron Prince On

The @ sign denotes attributes of a node. So if you want to return the value of the attribute Pagetitle where the Pagetype attribute is equal to Parent, it should read:

<xsl:value-of select= "/dsQueryResponse/Rows/Row[@Pagetype='Parent']/@Pagetitle" />

A helpful resource I use to test my XPATH is http://www.xmlme.com/XpathTool.aspx

1
Dimitre Novatchev On

With the provided XML document use:

/*/*/*[Pagetype = 'Parent']/Pagetitle

XSLT - based verification:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>

 <xsl:template match="/">
  <xsl:copy-of select="/*/*/*[Pagetype = 'Parent']/Pagetitle"/>
 </xsl:template>
</xsl:stylesheet>

when this transformation is applied on the provided XML document:

<dsQueryResponse>
       <Rows>
            <Row>
               <Title>1</Title>
               <Pagetype>Parent</Pagetype>
               <Pagetitle>title of page</Pagetitle>
            </Row>
        </Rows>
</dsQueryResponse>

the XPath expression is evaluated and all (in this case just one) selected nodes are output:

<Pagetitle>title of page</Pagetitle>
0
cathy On

Here's how I understand the problem: Find each Row with a child element Pagetype of 'Parent', display value of child element Pagetitle.

My solution: Create a node set of all Rows that fulfill the criteria then select value of child element Pagetitle.

<xsl:for-each select="/dsQueryResponse/Rows/Row[Pagetype='Parent']">
    <xsl:value-of select="Pagetitle" />
</xsl:for-each>