문제

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>?

도움이 되었습니까?

해결책

See ParentNode and LocalName properties:

if (title.ParentNode.LocalName == "entry") { ... }

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top