c# - 使用 lambda 语法在 LinqPad 中查询 XML 源

标签 c# xml linq lambda linqpad

考虑到存储在文件 xmlData.xml 中的以下 XML 数据,我尝试使用 LinqPad 使用 lambda 语法查询它。

我记得以前用过这个,但想不起来了。我可以使用属性查询数据,就像在 Visual Studio 中查询对象一样。

    <?xml version="1.0"?>
<ArrayOfHROps_User xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <HROps_User>
    <EntityKey>
      <EntitySetName>HROps_User</EntitySetName>
      <EntityContainerName>HROperationsEntities</EntityContainerName>
      <EntityKeyValues>
        <EntityKeyMember>
          <Key>UserID</Key>
          <Value xsi:type="xsd:int">44405</Value>
        </EntityKeyMember>
      </EntityKeyValues>
    </EntityKey>
    <UserID>44405</UserID>
    <EmployeeID>AAA40</EmployeeID>
    <Period>2015-06-17T00:00:00</Period>
    <Active>true</Active>
    <Options>false</Options>
    <Pager>false</Pager>
    <Contractor>false</Contractor>
    <TimeStamp>2015-06-18T13:37:38.3</TimeStamp>
    <UserName>Mark.Walsh</UserName>
  </HROps_User>
  <HROps_User>
    <EntityKey>
      <EntitySetName>HROps_User</EntitySetName>
      <EntityContainerName>HROperationsEntities</EntityContainerName>
      <EntityKeyValues>
        <EntityKeyMember>
          <Key>UserID</Key>
          <Value xsi:type="xsd:int">44406</Value>
        </EntityKeyMember>
      </EntityKeyValues>
    </EntityKey>
    <UserID>44406</UserID>
    <EmployeeID>AAA60</EmployeeID>
    <Period>2015-06-17T00:00:00</Period>
    <Active>true</Active>
    <Options>false</Options>
    <Pager>false</Pager>
    <Contractor>false</Contractor>
    <TimeStamp>2015-06-18T13:37:38.94</TimeStamp>
    <UserName>Mark.Walsh</UserName>
  </HROps_User>

在 LinqPad 中 - 这些语句加载数据并正确输出:

var myxml = XElement.Load (@"c:\temp\xmlData.xml");
myxml.Elements().Dump();

我希望以下内容也能起作用:

myxml.Elements().FirstOrDefault(x=>x.UserName == "Mark.Walsh").Dump();

但它给了我错误:

'System.Xml.Linq.XElement' does not contain a definition for 'UserName' and no extension method 'UserName' accepting a first argument of type 'System.Xml.Linq.XElement' could be found (press F4 to add a using directive or assembly reference)

同样,我记得以前有一个非常干净的语法,但我无法弄清楚它到底是怎么回事。 谢谢!

最佳答案

可能你的意思是使用 Element()将元素名称作为参数传递的方法:

myxml.Elements()
     .FirstOrDefault(x => (string)x.Element("UserName") == "Mark.Walsh")
     .Dump();

Dotnetfiddle Demo

关于c# - 使用 lambda 语法在 LinqPad 中查询 XML 源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30934145/

相关文章:

python - 跳出 while True 循环

xml - 评估属性值是否可解析为xs:int

Linq - 将查询表达式转换为点符号

c# - 如何在 ASMX 中实现 OAuth 2.0(网络引用)?

c# - 将 MMDDYYYY 转换为 01-JAN-YY

c# - 在 asp.net 应用程序中启用 c# 7

c# - c#执行完后关闭sqlcmd

C# - 从 XML 文档中的特定标记获取值

c# - 在列表列表中查找项目

c# - 使用 LINQ 将两个不同类型的 IQueryable 变量连接在一起