Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use XPathNavigator and return different nodes?

Tags:

c#

.net

xml

xslt

xpath

I have a XML file like this:

<Document>
   <Tests>
      <Test>
         <Name>A</Name>
         <Value>0.01</Value>
         <Result>Pass</Result>
      </Test>
      <Test>
         <Name>A</Name>
         <Value>0.02</Value>
         <Result>Pass</Result>
      </Test>
      <Test>
         <Name>B</Name>
         <Value>1.01</Value>
         <Result>Fail</Result>
      </Test>
      <Test>
         <Name>B</Name>
         <Value>0.01</Value>
         <Result>Pass</Result>
      </Test>
   </Tests>
</Document>

And a class to hold data for each Test:

public class TestData
{
   public string TestName {get; set;}
   public int TestPositon {get; set;} //Position of Test node in XML file
   public string TestValue {get; set;}
   public string TestResult {get; set;}
}

Now I am using this code to put all Test's in a List<TestData>

doc = new XPathDocument(filePath);
nav = doc.CreateNavigator();

private List<TestData> GetAllTestData()    
 {


    List<TestData> Datas = new List<TestData>();
    TestData testData;

    XPathNodeIterator it = nav.Select("/Document/Tests/Test/Name");

    int pos = 1;

    foreach(XPathNavigator val in it)
    {
       testData.TestPosition = pos;
       testData = new TestData();
       // This adds the Name, but what should I change to access Value and Result
       // in the same nav ??
       testData.TestName = val.Value; 
       Datas.Add(testData);
       pos++; //Increment Position
    }

    return Datas;
 }

So as I said in the comment, the XPath is only refering to Name node, how can I get all 3 nodes in a single foreach for the itterator? I mean how to assign this things aswell:

testData.Value = ???
testData.Result = ???

Thanks!

like image 988
Saeid Yazdani Avatar asked Feb 02 '26 15:02

Saeid Yazdani


1 Answers

Use XPath

/Document/Tests/Test

It selects test nodes. Then in foreach use XPathNavigator.SelectSingleNode:

foreach (XPathNavigator val in it)
{
    testData = new TestData();
    testData.TestPosition = pos;
    testData.TestName = val.SelectSingleNode(nav.Compile("Name")).Value;
    testData.TestValue = val.SelectSingleNode(nav.Compile("Value")).Value;
    Datas.Add(testData);
    pos++;
}

Or use this XPath:

/Document/Tests/Test/*

It selects all nodes.

like image 166
Kirill Polishchuk Avatar answered Feb 05 '26 05:02

Kirill Polishchuk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!