我正在使用以下代码
string xml = @"<?xml version='1.0' encoding='UTF-8'?>
<widgets>
<widget>
<url>~/Portal/Widgets/ServicesList.ascx</url>
<castAs>ServicesWidget</castAs>
<urlType>ascx</urlType>
<parameters>
<PortalCategoryId>3</PortalCategoryId>
</parameters>
</widget>
<widget>
<url>www.omegacoder.com</url>
<castAs>ServicesWidget</castAs>
<urlType>htm</urlType>
<parameters>
<PortalCategoryId>41</PortalCategoryId>
</parameters>
</widget>
</widgets>";
XDocument loaded = XDocument.Parse( xml );
var widgets = from x in loaded.Descendants( "widget" )
select new
{
URL = x.Descendants( "url" ).First().Value,
Category = x.Descendants( "PortalCategoryId" ).First().Value
};
foreach ( var wd in widgets )
Console.WriteLine( "Widget at ({0}) has a category of {1}", wd.URL, wd.Category );
这只为我提供了第一个小部件的URL和类别?不知道如何获得第二个的值。 另外,我如何获得小部件的索引,如0和1等等......取决于有多少个小部件。
感谢
答案 0 :(得分:2)
您的查询为我返回了两个小部件的条目,我已经尝试了您的代码而没有任何更改。
以下查询将帮助您获取每个小部件的索引:
var widgets = loaded.Descendants("widget").Select((w, i) =>
new
{
WidgetIndex = i,
URL = w.Descendants( "url" )
.FirstOrDefault()
.Value,
Category = w.Descendants("PortalCategoryId")
.FirstOrDefault()
.Value
});
字符串表示:
string widgetsInfo =
loaded.Descendants("widget")
.Select((w, i) =>
new
{
WidgetIndex = i,
URL = w.Descendants("url").FirstOrDefault().Value,
Category = w.Descendants("PortalCategoryId").FirstOrDefault().Value
})
.Select(w => String.Format("Index:{0}; URL:{1}; CATEGORY:{2}; ",
w.WidgetIndex, w.URL, w.Category))
.Aggregate((acc, next) => acc + Environment.NewLine + next);