Reading an XML in C#
-
29-09-2019 - |
Question
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>
?
Solution
See ParentNode and LocalName properties:
if (title.ParentNode.LocalName == "entry") { ... }
OTHER TIPS
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);
}
I suggest using XDocument
in the System.Xml.Linq
namespace.
Then you can simply write document.Elements("entry").Elements("title")
Have you tried something like entry/title as your xpath?
Here's a hint: look at how you iterate through the first "title" node.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow