简体   繁体   English

为什么只吃一个? Linq到XML C#

[英]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 :) ThemeItem只是一个带有公共字符串的获取集。当我写出这些数据时,我使用了一个转发器感谢您的帮助:)

That is because the Descendants extension method takes all decendants of the xml node, that is named "themes". 这是因为Descendants扩展方法采用了xml节点的所有后代,即“主题”。 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. 由于您的主题节点是各个主题标签的容器,因此只有一个,当您使用.Element时,您会第一个出现。

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() 尝试使用XElement.Load()而不是XDocument.Load()

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

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

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