Matjaz
Matjaz

Reputation: 484

XSLT value select based on multiple tags and it's values

I would like to know how to get value from below xml. I tried couple of different approaches and it seems I cannot find the correct solution.

<a>
    <aid>ok</aid>
    <b>
        <bid>ok</bid>
        <c>
            <cid>ok</cid>
            <d>
                <dValue>goal</dValue>
            </d>
        </c>
    </b>
</a>

Condition must meet below criteria:

Any help would be much appreciated as I've spent couple of hours on this already :) Oh, I'm using xslt 2.0.

Upvotes: 1

Views: 923

Answers (2)

Dimitre Novatchev
Dimitre Novatchev

Reputation: 243469

A more general task:

In case the names of the elements don't matter and the depth of the path (number of nested elements) can be any , but the children have as name the name of the parent appended with "id", then this XPath 2.0 expression produses the wanted result in all such cases, including the current one:

//dValue[every $anc in ../ancestor::* 
          satisfies $anc/*[name() eq concat($anc/name(), 'id')]/string() eq 'ok' ]/string()

XSLT 2.0 verification:

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output method="text"/>

  <xsl:template match="/">
    <xsl:sequence select=
    "//dValue[every $anc in ../ancestor::* 
       satisfies $anc/*[name() eq concat($anc/name(), 'id')]/string() eq 'ok' ]/string()"/>
  </xsl:template>
</xsl:stylesheet>

When this transformation is applied on the provided XML document:

<a>
    <aid>ok</aid>
    <b>
        <bid>ok</bid>
        <c>
            <cid>ok</cid>
            <d>
                <dValue>goal</dValue>
            </d>
        </c>
    </b>
</a>

it evaluates the expression and outputs the result of this evaluation:

goal

Applying the same transformation on this XML document:

<x>
    <xid>ok</xid>
    <y>
        <yid>ok</yid>
        <z>
            <zid>ok</zid>
            <t>
                <dValue>goal2</dValue>
            </t>
        </z>
    </y>
</x>

again produces the wanted correct result:

goal2

Upvotes: 1

Markus Jarderot
Markus Jarderot

Reputation: 89171

<xsl:value-of select="a[aid='ok']/b[bid='ok']/c[cid='ok']/d/dValue"/>

Upvotes: 3

Related Questions