views:

92

answers:

5

Hello,

I'm using System.Xml to read a xml file in C#. First I open the file (locally)... and use foreach to get the values, like this:

XmlNodeList titles = xmlDoc.GetElementsByTagName("title");
foreach (XmlNode title in titles)
{
rowNews = new ListViewItem();
rowNews.Text = (title.ChildNodes[0].Value);
listView1.Items.Add(rowNews);
}

The problem is, I have many rss tags called title in my file, I'd like to read only those what are inside <entry></entry>?

A: 

here's a hint, look at how you iterate through the first "title" node.

brian brinley
A: 

Have you tried something like entry/title as your xpath?

Mike Cheel
A: 

See ParentNode and LocalName properties:

if (title.ParentNode.LocalName == "entry") { ... }
LarsH
Thank you sir, I like your way the best and it works! Thank you everyone else also!
Badr Hari
The XPath approaches are good too. This is just a simpler way to do things if you are familiar with DOM and not with XPath.
LarsH
+7  A: 

Usually its easier to use XPaths in this case, so your code would look something like this:

XmlNodeList titles = xmlDoc.SelectNodes("//entry/title");
foreach (XmlNode title in titles)
{
rowNews = new ListViewItem();
rowNews.Text = (title.ChildNodes[0].Value);
listView1.Items.Add(rowNews);
}
Grzenio
+1  A: 

I suggest using XDocument in the System.Xml.Linq namespace.

Then you can simply write document.Elements("entry").Elements("title")

Noel Abrahams