2011-06-22 171 views
1

如果我有以下xml;Linq2XML创建对象模型

<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> 

如何使用Linq2XML创建对象heiarchy?

我试过这个;

var products = from xProducts in xDocument.Descendants("root").Elements("productList") 
    select new 
    { 
    product = from xProduct in xProducts.Elements("product") 
    select new 
    { 
     id = xProduct.Element("id").Value, 
     name = xProduct.Element("name").Value 
    } 
    } 

但是这会产生一个错误,因为我认为product正在多次声明。

我想结束一个这样的对象;

ProductList 
    List<product> 
    id 
    name 

我不能有一个模型,这些将进入,所以我需要使用var。

编辑

如果我只得到说这个名字还是那么的ID代码工作。它只会失败,如果我试图获得这两个领域。

+0

什么是错误? –

+0

类型'<> f__AnonymousType0 '同时存在于'MyApplication.dll'和'System.Web.dll' – griegs

回答

3

关于你的错误,你使用Silverlight吗?这不支持匿名类型。无论如何,Linq-to-XML在流利的语法而不是查询语法方面效果更好。定义合适的产品列表和产品类别,以下应该工作:

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 
    }); 
+0

是的,虽然解决了这个问题,但我真的很高兴不想真正拥有这个模型。 – griegs

相关问题