gpt4 book ai didi

c# - 如何使用 Linq Lambda 检索 XML?

转载 作者:太空宇宙 更新时间:2023-11-03 21:57:16 24 4
gpt4 key购买 nike

当 Databind() 调用时,它会在新客户处生成错误。请仅通过 linq with lambda 解决。

错误:

对象引用未设置为对象的实例

IEnumerable<Customers> Customers = XDocument.Load("Customers.xml")
.Descendants("Customer")
.Select(x => new Customers
{
Name = x.Element("Name").Value,
City = x.Element("City").Value,
Contact = x.Element("Contact").Value
});

grid.DataSource = Customers;
grid.DataBind();

public class Customers
{
public Customers() { }
public string Name { get; set; }
public string City { get; set; }
public string Contact { get; set; }
}

XML:

 <?xml version="1.0" encoding="utf-8"?>
<Customers>
<Customer>
<Name>John</Name>
<City>Ney York</City>
<Contact>2233</Contact>
</Customer>
<Customer>
<Name>Albert</Name>
<City>Sydney</City>
<Contact>4455</Contact>
</Customer>
<Customer>
<Name>David</Name>
<City>Colombo</City>
<Contact>6677</Contact>
</Customer>
<Customer>
<Name>George</Name>
<City>London</City>
<Contact>8899</Contact>
</Customer>
</Customers>

最佳答案

试试这个..

IEnumerable<Customers> Customers = XDocument.Load("Customers.xml").Element("Customers")
.Descendants("Customer")
.Select(x => new Customers
{
Name = x.Element("Name").Value,
City = x.Element("City").Value,
Address = x.Element("Address").Value
});

希望这个工作。

关于c# - 如何使用 Linq Lambda 检索 XML?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11735673/

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