简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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