griegs
griegs

Reputation: 22770

Linq2XML Create Object Model

If i have the following 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?

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.

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.

edit

If I only get say the name or the id then the code works. It only fails if I try to get both fields.

Upvotes: 1

Views: 965

Answers (1)

ColinE
ColinE

Reputation: 70162

Regarding your error, are you using Silverlight? this does not support anonymous types. Anyhow, Linq-to-XML works better with the fluent syntax rather than query syntax. Defining suitable ProductList and Product classes, the following should work:

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

Upvotes: 3

Related Questions