reox
reox

Reputation: 5237

Get attribute where subtag has attribute x

Consider this XML File structure

...
<sometag attr="foobar">
    <subtag>
        <subsubtag someattr="foo" />
        <subsubtag someattr="bla" />
        <subsubtag someattr="bar" />
    </subtag>
</sometag>
...

currently i have this XPath Query: /sometag/subtag/subsubtag[@someattr='foo'] which gets me these subsubtags. Is it possible to get the attr="foobar" from this query? so i want to have all attr from sometag where there is a subsubtag with someattr="foo".

Upvotes: 1

Views: 171

Answers (3)

Oleksandr.Bezhan
Oleksandr.Bezhan

Reputation: 2168

/sometag[subtag/subsubtag[@someattr="foobar"]]/@attr

or less strictly:

//sometag[//subsubtag[@someattr="foobar"]]/@attr

Upvotes: 1

ionutab
ionutab

Reputation: 444

On the xml file:

<root>
<sometag attr="foobar1"> 
  <subtag> 
    <subsubtag someattr="foo"/>  
    <subsubtag someattr="bla"/>  
    <subsubtag someattr="bar"/> 
  </subtag> 
</sometag>
<sometag attr="foobar2"> 
  <subtag> 
    <subsubtag someattr="foo"/>  
    <subsubtag someattr="bla"/>  
    <subsubtag someattr="bar"/> 
  </subtag> 
</sometag>
<sometag attr="foobar3">
    <subtag>
        <subsubtag someattr="f2342oo" />
        <subsubtag someattr="bla" />
        <subsubtag someattr="bar" />
    </subtag>
</sometag>
</root>

try:

/root/sometag/subtag/subsubtag[@someattr='foo']/../../@attr

I made a quick test on here, and it seems to be working for me.

Upvotes: 1

reox
reox

Reputation: 5237

another possibility i just found out:

/sometag/subtag/subsubtag[@someattr='foo']/../../@attr

you can use .. to select the parent node. you need to go up in hirachie and select the attribute.

Upvotes: 2

Related Questions