1

我有一个简单的用户 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
4

1 回答 1

2

您只需要按 studentId 进行过滤。应该:

var username = xmldoc.XPathSelectElement(String.Format("Students/Student[StudentId={0}]/StudentName", StudentId)).Value;
于 2012-06-16T07:50:03.677 回答