Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xpath - selection based on multiple criteria

Tags:

c#

xpath

I have the following XML File:

<persons>
   <person name="shawn">
      <age>34</age>
      <hair style="spikes">red</hair>
    </person>
    <person  name="mike">
       <age>36</age>
       <hair style="bald">red</hair>
    </person>
    <person name="shawn">
       <age>38</age>
       <hair style="bald">red</hair>
    </person>
</persons>

Using XPath in C#, is it possible to select the person element where the name is "Shawn", and the hair style = "bald"?

I tried using:

XElement.XPathSelectElement("//person[@name='shawn'] | //person/hair[@style='bald']

but that gives me a reference to the hair element, and not the person element.

Thanks in advance :)

Peter

like image 480
SchmitzIT Avatar asked Jan 16 '23 09:01

SchmitzIT


1 Answers

If you want someone who is both called shawn and is bald (which your question title suggests), you want:

//person[@name='shawn' and hair/@style='bald']

If you want people who are either called shawn or are bald (which it looks like you may do from the attempt in your question), you want:

//person[@name='shawn' or hair/@style='bald']
like image 68
actionshrimp Avatar answered Jan 25 '23 16:01

actionshrimp