无法使用xpath从XDocument中提取值

时间:2012-06-16 07:44:59

标签: c# .net xpath

我有一个简单的xml用户。我有StudentId,我只需要根据studentid从xml中获取学生姓名。似乎很简单,但我无法使用xpath完成它。

这是xml:

<Students>
  <Student>
    <StudentId>1</StudentId>
    <StudentName>Mad</StudentName>
  </Student>
  <Student>
    <StudentId>2</StudentId>
    <StudentName>Cad</StudentName>
  </Student>
</Students>

这是我的代码:

XDocument xmldoc = XDocument.Load(Server.MapPath("~/xmlsample.xml"));

string StudentId = "2"; // id to be selected

var username = xmldoc.XPathSelectElement("Students/Student/StudentName").Value;// Not sure how to use where condition here

1 个答案:

答案 0 :(得分:2)

您只需按studentId过滤即可。应该是:

var username = xmldoc.XPathSelectElement(String.Format("Students/Student[StudentId={0}]/StudentName", StudentId)).Value;