当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - getting a value in XPATH when only I know something about it descendants?

问题描述:

Imagine a xml file like this:

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

I use a method to access the B value, but I need to get name A as well, but I only now that value B exist in my XML file (doc is 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;

}

So, the question is, how can I access A in the above method?

网友答案:

You can use this XPath:

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

or:

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;
网友答案:

Here is the xpath expression to read A:

/Document/Tests/Test[Subtest/Test/Name = 'B']/Name
分享给朋友:
您可能感兴趣的文章:
随机阅读: