sanjay
sanjay

Reputation: 1020

XSLT - conditionally check element exist in Xpath

I have a xml like follows,

<doc>
  <a>
    <b></b>
  </a>
  <a></a>
  <a>
    <b></b>
  </a>
  <a>
    <c></c>
  </a>
  <a></a>
</doc>

what i need to do is if <a> has a <b> child (one or more) add <end> tag just before the end of the <a>node. if <a> has not <b> child do nothing.

so the result xml should be,

   <doc>
      <a>
        <b></b>
        <end></end>
      </a>
      <a></a>
      <a>
        <b></b>
        <b></b>
        <end></end>
      </a>
      <a>
        <c></c>
      </a>
      <a></a>
    </doc>

I cannot think about a way that how I should conditionally check in xpath to check if <b> child is existing or not in <a>.

I cannot use,

 <xsl:template match="a//b">
        <xsl:copy>
            <xsl:apply-templates select="@* | *"/> 
            <end></end>
        </xsl:copy>
    </xsl:template>

this adds <end> nodes to every <b> node.

Any suggestions how can I do this?

Thanks in advance

Upvotes: 0

Views: 212

Answers (1)

har07
har07

Reputation: 89325

You can use a[b] to match <a> that has one or more child <b> :

<xsl:template match="a[b]">
    <xsl:copy>
        <xsl:apply-templates select="@* | *"/> 
        <end></end>
    </xsl:copy>
</xsl:template>

or maybe a[.//b] if you rather meant to match <a> that has one or more descendant <b>.

Upvotes: 1

Related Questions