Domanda

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!

È stato utile?

Soluzione

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.

Altri suggerimenti

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

this will return you all the document elements which has Tests/Test/Name inside them

now you can be sure that if you scan document - you will have the 3 leafs.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top