XSLT - How to select XML Attribute by Attribute?
Asked Answered
T

5

27

this is the structure of my source xml:

<root>
<DataSet Value="A">
<Data Value1="1" Value2="anythingA1" />
<Data Value1="2" Value2="anythingA2" />
<Data Value1="3" Value2="anythingA3" />
<Data Value1="4" Value2="anythingA4" />
<Data Value1="5" Value2="anythingA5" />
</DataSet>
</root>

from which I like to create some variables e.g. from all with Value1="2" and all with Value1="5" should result myVar1 with anythingA2 and myVar2 with anythingA5

My approch looks like this

<xsl:variable name="myVarA" select="/DataSet/Data/[@Value1='2']/@Value2" />

but of course is not working since Value2 is no child of Value1.

thanks for any hints in advance!

Triton answered 12/2, 2009 at 14:5 Comment(0)
T
49

Just remove the slash after Data and prepend the root:

<xsl:variable name="myVarA" select="/root/DataSet/Data[@Value1='2']/@Value2"/>
Torquay answered 12/2, 2009 at 14:8 Comment(1)
@Andrew Hare: Corrected. Thanks to Quassnoi for elaborating, I lost connection immediately after posting the first revision.Torquay
A
4

There are two problems with your xpath - first you need to remove the child selector from after Data like phihag mentioned. Also you forgot to include root in your xpath. Here is what you want to do:

select="/root/DataSet/Data[@Value1='2']/@Value2"
Antetype answered 12/2, 2009 at 14:12 Comment(0)
S
1

Try this

xsl:variable name="myVarA" select="//DataSet/Data[@Value1='2']/@Value2" />

The '//' will search for DataSet at any depth

Samul answered 12/2, 2009 at 14:16 Comment(0)
W
1

Note: using // at the beginning of the xpath is a bit CPU intensitve -- it will search every node for a match. Using a more specific path, such as /root/DataSet will create a faster query.

Wretched answered 12/2, 2009 at 14:46 Comment(1)
As this does not answer the question, it should be a comment on the OP's question.Shay
P
0

I would do it by creating a variable that points to the nodes that have the proper value in Value1 then referring to t

<xsl:variable name="myVarANode" select="root//DataSet/Data[@Value1='2']" />
<xsl:value-of select="$myVarANode/@Value2"/>

Everyone else's answers are right too - more right in fact since I didn't notice the extra slash in your XPATH that would mess things up. Still, this will also work , and might work for different things, so keep this method in your toolbox.

Pharyngology answered 12/2, 2009 at 14:35 Comment(1)
Is the 1, 2, 3 stuff hypothetical? I've got <cd><album>Album Name</album><artist>Artist A</artist><artist>Artist B></artist></cd>, and I am trying to select all sibling artists and tie them to an intermediary table connected to the album, without having duplicate artists from my enormous database. Any ideas?Recto

© 2022 - 2024 — McMap. All rights reserved.