0

我有一个 XElement 对象,它是从如下所示的 XML 构建的:

<Root>
  <Oppurtunities>
    <Oppurtunity>
      <Title> Account Manager</Title>
      <Company>Company name</Company>
      <Location>Boston</Location>
      <EndDate>2013-04-11</EndDate>
      <c>acce</c>
      <id>MNYN-95ZL8L</id>
      <Description>This is a detailed description...</Description>
    </Oppurtunity>

现在我需要从特定的 Oppurtunity 节点获取描述值,这意味着我想从 id 特定的位置获取描述。我需要做这样的事情:

//My XElement object is called oppurtunities
oppurtunities = new XElement((XElement)Cache["Oppurtunities"]);

string id = Request.QueryString["id"];

//I want to do something like this but of course this is not working
var description = (from job in oppurtunities
                              .Element("Oppurtunities")
                              .Element("Oppurtunity")
                              .Element("Description")
                              where job.Element("id") == id).SingleOrDefault();
4

1 回答 1

0

您必须.Element("Description")在查询中进一步移动,以允许id条件工作:

//I want to do something like this but of course this is not working
var description = (from job in oppurtunities
                              .Element("Oppurtunities")
                              .Elements("Oppurtunity")
                   where job.Element("id") == id
                   select job.Element("Description")).SingleOrDefault()

Element("id")作为字符串进行比较,请使用(string)XElement转换 - 即使<id>找不到它也会起作用:

where (string)job.Element("id") == id

使用XElement.Value会抛出NullReferenceException这种情况。

于 2013-04-09T08:22:17.587 回答