Rob
Rob

Reputation: 10248

Help with Linq to Xml query

I have the following xml in an XDocument (confirmed by checking in the debugger) generated using XDocument.Parse(myXmlString)

<Size>
    <row SizeId="239" Title="XXS" Quantity="20"/>
    <row SizeId="240" Title="XS" Quantity="15"/>
    <row SizeId="241" Title="S" Quantity="12"/>
    <row SizeId="242" Title="M" Quantity="18"/>
</Size>

I am trying to convert it to a list of objects declared as:

public class SizeQuantityXml
{
    public int SizeId { get; set; }
    public string Title { get; set; }
    public int Quantity { get; set; }
}

But when I do this the sizeQuantityXmlList only has the first "row" in it:

List<SizeQuantityXml> sizeQuantityXmlList = 

(from x in xDocument.Descendants("Size")
 select new SizeQuantityXml() { SizeId = (int)x.Element("row").Attribute("SizeId"),
                                Title = (string)x.Element("row").Attribute("Title"),
                                Quantity = (int)x.Element("row").Attribute("Quantity") }
).ToList();

This is my first Linq to XML attempt any suggestion greatly appreciated :-)

Upvotes: 3

Views: 122

Answers (1)

k.m
k.m

Reputation: 31444

You're querying for Size elements - which you got only one. You want collection of rows instead:

var query = from row in xDocument.Element("Size").Descendants("row")
            select new SizeQuantityXml()
            { 
                SizeId = (int)row.Attribute("SizeId"),
                Title = (string)row.Attribute("Title"),
                Quantity = (int)row.Attribute("Quantity") 
            };

var sizeQuantityXmlList = query.ToList();

Edit:

Proposed solution won't work if your XML differs from what you posted (eg. is wrapped by more parent tags). Try Descendants("Size").Descendants("row") as was proposed originally.

Upvotes: 3

Related Questions