【问题标题】:Select from XElement with where statement using linq使用 linq 从带有 where 语句的 XElement 中选择
【发布时间】:2015-04-13 06:27:07
【问题描述】:

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

【问题讨论】:

    标签: linq-to-xml xelement


    【解决方案1】:

    您必须在查询中进一步移动.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 转换-即使找不到&lt;id&gt;,它也可以工作:

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

    在这种情况下使用XElement.Value 将抛出NullReferenceException

    【讨论】:

    • 谢谢!做到了。我只需要设置 where job.Element("id").Value 因为它与字符串进行比较。
    猜你喜欢
    • 2019-11-07
    • 2019-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多