【问题标题】:Returns exception "Expression cannot contain lambda expressions" when getting XML document using LINQ使用 LINQ 获取 XML 文档时返回异常“表达式不能包含 lambda 表达式”
【发布时间】:2014-02-13 09:08:40
【问题描述】:

我想从 XML 文档中使用 linq 获取 XElement。

我的 linq 查询是:

webDetails.Descendants("WebApplications")
          .Descendants("WebApplication")
          .Where(x => x.Attribute("Uri").Value.Equals(selectedItem.Value))
          .FirstOrDefault();

该文件包含以下 xml 节点:

<?xml version="1.0" encoding="UTF-8"?>
<WebApplications>
  <WebApplication Name="SharePoint - 80" Uri="http://xxxx/">
    <SiteCollections>
      <SiteCollection>
        <RootWeb Title="Root" Url="/">
          <Webs />
        </RootWeb>
      </SiteCollection>
      <SiteCollection>
        <RootWeb Title="My Site Host" Url="/my/HostSite">
          <Webs />
        </RootWeb>
      </SiteCollection>
    </SiteCollections>
  </WebApplication>
  <WebApplication Name="SharePoint - 9999" Uri="http://xxx/">
    <SiteCollections>   
        <SiteCollection>
        <RootWeb Title="Ritesh Goswami" Url="/my/rami">
          <Webs />
        </RootWeb>
      </SiteCollection>
      <SiteCollection>
        <RootWeb Title="Riyaz Kalva" Url="/my/rialva">
          <Webs />
        </RootWeb>
      </SiteCollection>
    </SiteCollections>
  </WebApplication>
</WebApplications>

如果我执行如下查询:

webDetails.Descendants("WebApplications").Descendants("WebApplication").First()

我得到了第一个元素,但是当我使用属性值进行过滤时,我得到了上述错误。 使用属性值过滤xmlelement应该怎么做?

【问题讨论】:

  • 请发布准确错误信息。代码对我来说看起来不错。
  • 在一个小型测试应用程序中,编译没有问题。 (我个人会使用doc.Root.Elements("WebApplication").FirstOrDefault(x =&gt; (string) x.Attribute("Uri") == selectedItem.Value),但那是另一回事。
  • 另外请提供更多上下文 - 如果这是一个异常,你是如何使用查询的?理想情况下,发布一个简短但完整的程序来演示问题。
  • 我试过你的代码,它工作正常,xml 格式错误,刚刚修复了这个问题,我得到了带有过滤器的第二个元素

标签: c# xml linq lambda


【解决方案1】:

尝试使用这个:

webDetails.Descendants("WebApplications").Descendants("WebApplication").Where(x => string.Equals(x.Attribute("Uri").Value, selectedItem.Value, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();

【讨论】:

    【解决方案2】:

    试试这个...

    string s = selectedItem.Value;
    webDetails.Descendants("WebApplications").Descendants("WebApplication").Where(x => x.Attribute("Uri").Value.Equals(s)).FirstOrDefault();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-06-21
      • 2018-09-29
      • 1970-01-01
      • 1970-01-01
      • 2016-10-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多