我无法弄清楚为什么我的代码只采用第一个标签,而不是其余的.
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();
Run Code Online (Sandbox Code Playgroud)
ThemeItem只是一个带有公共字符串的get set当我写出这个数据时我使用了一个转发器感谢您的帮助:)
这是因为Descendants扩展方法获取了xml节点的所有后代,名为"themes".由于您的主题节点是单个主题标记的容器,因此只有一个,当您使用.Element时,您将获得第一个出现.
这段代码应该有效:
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,
};
Run Code Online (Sandbox Code Playgroud)