C# Linq2XML创建对象模型
如果我有以下xmlC# Linq2XML创建对象模型,c#,linq-to-xml,C#,Linq To Xml,如果我有以下xml <productList> <product> <id>1</id> <name>prod 1</name> </product> <product> <id>2</id> <name>prod 2</name> </product> <product>
<productList>
<product>
<id>1</id>
<name>prod 1</name>
</product>
<product>
<id>2</id>
<name>prod 2</name>
</product>
<product>
<id>3</id>
<name>prod 3</name>
</product>
</productList>
但是,这会产生一个错误,因为我认为产品
被声明了不止一次
我想以这样一个物体结束
ProductList
List<product>
id
name
ProductList
列表
身份证件
名称
我不能有一个模型,这些将进入,所以我需要使用var
编辑
如果我只知道姓名或id,那么代码就可以工作了。只有尝试获取这两个字段时才会失败。关于您的错误,您是否使用Silverlight?这不支持匿名类型。无论如何,LINQtoXML使用流畅的语法比使用查询语法更好。定义合适的ProductList和产品类别时,应采用以下方法:
class ProductList : List<Product>
{
public ProductList(items IEnumerable<Product>)
: base (items)
{
}
}
class Product
{
public string ID { get; set;}
public string Name{ get; set;}
}
var products = xDocument.Desendants("product");
var productList = new ProductList(products.Select(s => new Product()
{
ID = s.Element("id").Value,
Name= s.Element("name").Value
});
类产品列表:列表
{
公共产品列表(项IEnumerable)
:基本(项目)
{
}
}
类产品
{
公共字符串ID{get;set;}
公共字符串名称{get;set;}
}
var products=xDocument.Desendants(“产品”);
var productList=newproductlist(products.Select(s=>newproduct())
{
ID=s.元素(“ID”).值,
Name=s.Element(“Name”).Value
});
MyApplication.dll和System.Web.dll中都存在类型“f_uAnonymousType0”是的,这解决了这个问题,但我非常不想实际使用该模型。
class ProductList : List<Product>
{
public ProductList(items IEnumerable<Product>)
: base (items)
{
}
}
class Product
{
public string ID { get; set;}
public string Name{ get; set;}
}
var products = xDocument.Desendants("product");
var productList = new ProductList(products.Select(s => new Product()
{
ID = s.Element("id").Value,
Name= s.Element("name").Value
});