gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 10:28:44 25 4
gpt4 key购买 nike

考虑到存储在文件 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com