简体   繁体   中英

Why take just one? Linq to XML C#

I can't figure out why my code just taking the first tag and not the rest.

var xml = XDocument.Load(HttpContext.Current.Server.MapPath("~/App_Data/Themes.xml"));

var q = from f in xml.Descendants("themes")
        select new ThemesItem
        {
            Name = f.Element("theme").Element("name").Value,
            Description = f.Element("theme").Element("description").Value,
            Author = f.Element("theme").Element("author").Value,
        };

return q.ToList();

ThemeItem is just a get set with public string When i write out this data i use a repeater Thanks for help :)

That is because the Descendants extension method takes all decendants of the xml node, that is named "themes". Since your themes node is the container for the individual theme tags, there is only one, and when you take .Element on that, you get the first occurence.

This code should work:

var q = from f in xml.Descendants("theme")
        select new ThemesItem
        {
            Name = f.Element("name").Value,
            Description = f.Element("description").Value,
            Author = f.Element("author").Value,
        };
<themes>
  <theme>
    <name>Standard</name>
    <description>standard theme</description>
    <author>User 1</author>
    <folder>standard</folder>
  </theme>
  <theme>
    <name>Standard</name>
    <description>standard theme</description>
    <author>User 2</author>
    <folder>standard</folder>
  </theme>
</themes>

Try using XElement.Load() instead of XDocument.Load()

http://msdn.microsoft.com/en-us/library/bb675196.aspx

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