Harvey Darvey
Harvey Darvey

Reputation: 714

xsl and xpath : search for a node inside a node, and return the value of an attribute in the found node

I have the below xml :

<w:style w:styleId="John">
  <w:name w:val="Peter" />
</w:style>

So basically, having the value of "Peter", I would like to get the value of "John" (which I would not know at that moment). There will be a lot of "w:style" nodes in my xml.

How do I get the value of "John" string returned to me using xslt (and xpath) 1.0 (preferably calling a named template to return the value)?

Upvotes: 1

Views: 290

Answers (1)

Ian Roberts
Ian Roberts

Reputation: 122364

A basic XPath expression that will extract what you need is

//w:style[w:name/@w:val = 'Peter']/@w:styleId

but as you've tagged your question "XSLT" and you say you have many of these nodes you might be better off using a key

<xsl:key name="nameByVal" match="w:name" use="@w:val" />

and then you can more efficiently query using

key('nameByVal', 'Peter')/../@w:styleId

or if the w:name might be nested inside other elements rather than a direct child of w:style then

key('nameByVal', 'Peter')/ancestor::w:style/@w:styleId

Upvotes: 2

Related Questions