[英]Why take just one? Linq to XML C#
我不知道为什么我的代码只使用第一个标签,而不使用其余标签。
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只是一个带有公共字符串的获取集。当我写出这些数据时,我使用了一个转发器感谢您的帮助:)
这是因为Descendants扩展方法采用了xml节点的所有后代,即“主题”。 由于您的主题节点是各个主题标签的容器,因此只有一个,当您使用.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,
};
<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>
尝试使用XElement.Load()而不是XDocument.Load()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.