只有在我了解它的后代时才能获得XPATH中的值?

时间:2011-11-20 19:33:30

标签: c# .net xml linq xpath

想象一下像这样的xml文件:

<Document>
   <Tests>
      <Test>
          <Name>A</Name>
          <SubTest>
              <Test>
                 <Name>B</Name>
                 <Value>100</Value>
              </Test>
           </SubTest>
       </Test>
      <Test>
          <Name>C</Name>
          <SubTest>
              <Test>
                 <Name>D</Name>
                 <Value>200</Value>
              </Test>
           </SubTest>
       </Test>
    </Tests> 
</Document>

我使用方法来访问B值,但我也需要获得名称A,但我现在只在我的XML文件中存在值B({{ 1}}是doc):

XmlDocument

所以,问题是,如何在上述方法中访问public class TestData { public string Parent {get;set;} public string Name {get; set;} public int Value {get;set;} } private TestData GetResult(string name) { TestData data = new TestData(); data.Name = name; data.Value = int.Parse(doc.SelectSingleNode("Document/Tests/Test/SubTest/Test[Name = '" + name + "']/Value").InnerText); data.Parent = null; //How can I get string A using the above xpath return data; }

2 个答案:

答案 0 :(得分:3)

您可以使用此XPath:

Document/Tests/Test[SubTest/Test/Name = 'B']/Name

或:

var nodeTest = 
    doc.SelectSingleNode("Document/Tests/Test[SubTest/Test/Name = 'B']");

var name = nodeTest.SelectSingleNode("Name").InnerText;
var value = nodeTest.SelectSingleNode("SubTest/Test/Value").InnerText;

答案 1 :(得分:2)

这是读取A:

的xpath表达式
/Document/Tests/Test[Subtest/Test/Name = 'B']/Name