简体   繁体   English

Linq2XML创建对象模型

[英]Linq2XML Create Object Model

If i have the following xml; 如果我有以下xml;

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

How would I use Linq2XML to create an object heiarchy? 我将如何使用Linq2XML创建对象层次结构?

I have tried this; 我已经尝试过了

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

However this produces an error because I think the product is being declared more than once. 但是,这会产生错误,因为我认为该product被声明了多次。

I'd like to end up with an object like this; 我想结束一个这样的对象;

ProductList
  List<product>
    id
    name

I can't have a model that these will go into so I need to use var. 我没有模型可以进入这些模型,因此我需要使用var。

edit 编辑

If I only get say the name or the id then the code works. 如果仅说出名称或ID,则代码有效。 It only fails if I try to get both fields. 仅当我尝试同时获取两个字段时,它才会失败。

Regarding your error, are you using Silverlight? 关于您的错误,您正在使用Silverlight吗? this does not support anonymous types. 这不支持匿名类型。 Anyhow, Linq-to-XML works better with the fluent syntax rather than query syntax. 无论如何,Linq-to-XML使用流利的语法而不是查询语法会更好地工作。 Defining suitable ProductList and Product classes, the following should work: 定义合适的ProductList和Product类,以下方法应该起作用:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM