Silverlight WP7 App从XML文件中提取错误的内容

时间:2010-11-14 00:47:04

标签: xml silverlight visual-studio-2010 windows-phone-7

更新:我为我用来访问XML文件内容的代码提供了更好的上下文。

我正在制作一个Windows Phone 7应用程序,我在其中访问在线XML文件。但是,文件的结构方式导致我从文件中提取错误的项目。

以下是文件的一般结构:

<?xml version="1.0"?>
<rss version="2.0">
<channel>
  <title>XML File Title</title>
  <link>http://www.url.com</link>
  <description>Description</description>
  <item>
     <title>Title of first item</title>
     <description>Description of first item</description>
  </item>
  <item>
     <title>Title of second item</title>
     <description>Description of second item</description>
  </item>
</channel>

我的代码导致我从文件顶部提取标题和说明,而不是每个项目中的标题和说明。这是我的代码:

XElement xmlitem = XElement.Parse(e.Result);

        var list = new List<datainfoViewModel>();

        foreach (XElement item in xmlitem.Elements("channel"))

        {
            var title = item.Element("title").Value;
            var description = item.Element("description").Value;


            list.Add(new datainfoViewModel
            {
                Title = title,
                Description = description,
            });

我知道我做错了什么,我只是不确定如何更改代码来修复它。提前感谢您提供的任何帮助!

3 个答案:

答案 0 :(得分:2)

尝试过更改:

foreach (XElement item in xmlitem.Elements("channel"))

foreach (XElement item in xmlitem.Element("channel").Elements("item"))

当你的代码正在按你所说的发生时,它循环遍历所有“通道”项目,在你的情况下只有一个,它有一个描述和标题,但你想要的是一个项目,这是一个频道的孩子。

答案 1 :(得分:1)

最简单的方法是逐个隧道(使用LinqToXml),逐个节点缩小查询范围,直到留下item个元素的集合。现在您可以选择正确的值。我就是这样做的:

var xmlitem=
    XDocument.Parse(
        @"<?xml version=""1.0""?><rss version=""2.0""><channel>  <title>XML File Title</title>  <link>http://www.url.com</link>  <description>Description</description>  <item>     <title>Title of first item</title>     <description>Description of first item</description>  </item>  <item>     <title>Title of second item</title>     <description>Description of second item</description>  </item></channel></rss>"
    );
var list =
    xmlitem
        .Element("rss")
        .Element("channel")
        .Elements("item")
        .Select(e=>new datainfoViewModel
            {
                Title=e.Element("title").Value,
                Description=e.Element("description").Value
            }
        )
        .ToList();

答案 2 :(得分:0)

以本文中使用的形式试用您的LINQ。

binding a Linq datasource to a listbox

代替“人”,请求“项目”。