简体   繁体   English

帮助 Linq 到 Xml 查询

[英]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)我在使用 XDocument.Parse(myXmlString) 生成的 XDocument(通过检查调试器确认)中有以下 xml

<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:但是当我这样做时, sizeQuantityXmlList 中只有第一个“行”:

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:-)这是我的第一个 Linq 到 XML 尝试任何建议,非常感谢:-)

You're querying for Size elements - which you got only one.您正在查询Size元素 - 您只有一个。 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).如果您的 XML 与您发布的内容不同(例如,被更多父标签包裹),建议的解决方案将不起作用。 Try Descendants("Size").Descendants("row") as was proposed originally.按照最初的建议尝试Descendants("Size").Descendants("row")

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

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