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>
?
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")
这是一个提示:看看你如何遍历第一个“标题”节点。
您是否尝试过类似入口/标题的xpath?
请参见ParentNode和LocalName属性:
if (title.ParentNode.LocalName == "entry") { ... }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.