Reputation: 205
UPDATE: I provided better context for the code which I was using to access the contents of the XML file.
I am making a Windows Phone 7 app in which I access an online XML file. However, the way the file is structured is causing me to pull the wrong items from the file.
Here is the general structure of the file:
<?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>
My code is causing me to pull the title and description from the top of the file, instead of the title and description within each item. Here's my code:
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,
});
I know what I'm doing wrong, I'm just not sure how to change the code to fix it. Thanks in advance for any help you can provide!
Upvotes: 0
Views: 493
Reputation: 4576
Have tried changing:
foreach (XElement item in xmlitem.Elements("channel"))
to
foreach (XElement item in xmlitem.Element("channel").Elements("item"))
As your code is doing what you say is happening it loops through all the "channel" items which there is only one in your case, which has a description and title, however the one you want is an item, which is a child of channel.
Upvotes: 2
Reputation: 120498
Easiest way is to tunnel down (using LinqToXml), node by node to narrow the scope of your query until you are left with a collection of item
elements. Now you can select the right values. Here's how I'd do it:
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();
Upvotes: 1
Reputation: 14882
Try your LINQ in the form used in this post.
binding a Linq datasource to a listbox
In place of "person", ask for "item".
Upvotes: 0