SelectNodes with Filter

user2353545 picture user2353545 · May 8, 2013 · Viewed 8.6k times · Source

Here is my xml:

<Instrument RecordCount="3" >
    <Department id = 18384, Sequence=1>
    <InstrumentData StatusCode="1" RoleType="ED" Style="X" DataOther='Data'>
</Department>
<Department id = 18465, Sequence=2>
     <InstrumentData StatusCode="2" RoleType="CD" Style="S" DataOther='Data'>
</Department>
<Department id = 16473, Sequence=3>
    <InstrumentData StatusCode="1" RoleType="CD" Style="T" DataOther='Data'>
</Department>
 </Instrument>

I want @Status attribute ='1' or '2' and not @RoleType='E' and 'F' and @Style ='S' and 'T' for each node.

I have the following statement, but it does not bring back the correct results.

XmlNodeList nodeList = root.SelectNodes(@"//Department[InstrumentData/@Status='1' or Department[InstrumentData/@Status='1' and not (Department[InstrumentData/@RoleType='E' or Department[InstrumentData/@RoleType='F') and (Department[InstrumentData/@Style='S' or Department[InstrumentData/@Style='T') ]", manager);

Or do I first need to get the first condition, then build xml doc, then get next condition.

Thanks.

Answer

hr_117 picture hr_117 · May 9, 2013

There is no problem to have complex conditions in xpaht expressions. But your example can not work because of some mistakes.
* Some brackets (]) are missing
* There is no Status attribute in your example xml.
* You cant use "or" to put together a note list.

Example: If you try to get Departments with InstrumentData/@StatusCode = 2 and Departments with InstrumentData/@Style= T.

The following will not work:

nodeList = root.SelectNodes("//Department[InstrumentData/@StatusCode='2'] or //Department[InstrumentData/@Style='T' ]");

But you can do either:

nodeList = root.SelectNodes("//Department[InstrumentData/@StatusCode='2'] | //Department[InstrumentData/@Style='T' ]");

Or (in my view better):

nodeList = root.SelectNodes("//Department[InstrumentData/@StatusCode='2' or InstrumentData/@Style='T' ]");