João Paulo
João Paulo

Reputation: 51

XPath, how to select nodes based in 2 conditions with attribute dependency

I'm struggling to merge 2 conditions in my XPath query with attribute dependence.

I want to select all the nodes with AdjsCI = 4005 and AdjsRNCid=280

<managedObject class="ADJS">
  <p name="AdjsCI">4005</p>
  <p name="AdjsRNCid">280</p>
</managedObject>

For a single condition it works fine, but I don't find for 2.

With 1 condition:

SelectNodes("//managedObject/p[@name='AdjsCI'][text()='4005']");

This one is OK.

But with 2 I've tried many many options but none worked.

SelectNodes("//managedObject/p[@name='AdjsCI' and @name='AdjsRNCid][text()='4005' and text()='280']");

SelectNodes("//managedObject/p[[@name='AdjsCI'][text()='4005] and [@name='AdjsRNCid][text()='280']]");

SelectNodes("//managedObject/p[@name='AdjsCI'][text()='4005'] and //managedObject/p[@name='AdjsRNCid'][text()='280']");

Is there a solution for this?

Thank you very much in advance.

João Paulo

Upvotes: 1

Views: 1951

Answers (2)

Sai
Sai

Reputation: 247

You have a couple of options purely based on the xml in the question.

1.

SelectNodes("//managedObject/p[contains(@name,'Adjs') and (text()='4005' or text()='280')]");

2.

SelectNodes("//managedObject/p[(@name,'AdjsCI' or @name='AdjsRNCid') and (text()='4005' or text()='280')]");
    3.

You can make the xpath more generic if you want to select the nodes without the data dependency. For example,

SelectNodes("//managedObject/p[contains(@name,'Adjs')); 

This will select any node that contains Ajds in the name attribute.

There are more options such as regular expressions that can be used as well. But this should address the issue you're facing for the moment.

Upvotes: 0

AakashM
AakashM

Reputation: 63340

You are on the right track. You need to put the and within the predicate (the [] condition), being sure to have it relative to the node being considered:

//managedObject[p[@name='AdjsCI']=4005 and p[@name='AdjsRNCid']=280]

Note that in cases such as yours where the entirety of the element's contents is what you're comaparing against, you don't need text().

Upvotes: 2

Related Questions