繁体   English   中英

使用linq从XElement中通过where语句选择

[英]Select from XElement with where statement using linq

我有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();

您必须在查询中进一步移动.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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM