atif
atif

Reputation: 1147

how to get first child node value of a parent element

I have an xml like below, what I am trying to do is to fetch the text node of parent element using a match template.

<xml>
  <para>
    <text>
        para 1
    </text>
    <para>
      <text>
        para 2
      </text>     
    </para>
  </para>
</xml>

my xslt looks like below

<xsl:template match="para">
          <xsl:value-of select="../para/text/text()"/>
</xsl:template> 

for first para node it is not returning any text which is good but for 2nd one it is returning para 1 para 2 where as it should return only para 1. Any help or hint how to achieve this?

Upvotes: 1

Views: 4449

Answers (1)

Borodin
Borodin

Reputation: 126722

In your XML, the parent of the second para element is the first para element. That means that, if the second para is your context node then ../para/text/text() will go up to the parent (the first para) down to all para children (there is only one - the second para again) and then select the text within the text child of that, which is para 2.

If you want the first text node of the parent para element then you should write

select="parent::para/text[1]"

However you need to write an apply-templates within the template so that the inner elements will be processed.

Upvotes: 1

Related Questions