如何使用XPathNavigator并返回不同的节点?

时间:2011-11-14 12:07:49

标签: c# .net xml xpath xpathnodeiterator

我有一个像这样的XML文件:

<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>

用于保存每个测试数据的类:

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;}
}

现在我使用此代码将所有测试放在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;
 }

正如我在评论中所说,XPath仅引用Name节点,如何在itterator的单个foreach中获取所有3个节点?我的意思是如何分配这些东西:

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

谢谢!

2 个答案:

答案 0 :(得分:7)

使用XPath

/Document/Tests/Test

选择测试节点。然后在foreach中使用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++;
}

或者使用此XPath:

/Document/Tests/Test/*

选择所有节点。

答案 1 :(得分:1)

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

这将返回所有包含测试/测试/名称的文档元素

现在您可以确定,如果您扫描文档 - 您将拥有3片叶子。