解析XmlReader中的XML元素
我正在构建一个需要运行XML feed的应用程序,但是我在获取某些元素方面遇到了一些麻烦。
我正在使用Twitter提要并希望运行所有元素。 我可以很好地连接并从feed中获取内容,但是当我通过
reader.Read();
时,我无法弄清楚如何只选择item
元素reader.Read();
。
谢谢你的帮助!
最简单的方法是使用XPath。 示例如下。
string xml = @" Twitter public timeline http://twitter.com/public_timeline Twitter updates from everyone! en-us 40 -
yasu_kobayashi: rTwT: @junm : yayaya yasu_kobayashi: rTwT: @junm : yayaya Tue, 28 Oct 2008 12:04:48 +0000 http://twitter.com/yasu_kobayashi/statuses/978829930 http://twitter.com/yasu_kobayashi/statuses/978829930 -
FreeGroup: WikiFortio - foobar http://tinyurl.com/5gvttf FreeGroup: WikiFortio - foobar http://tinyurl.com/5gvttf Tue, 28 Oct 2008 12:04:47 +0000 http://twitter.com/FreeGroup/statuses/978829929 http://twitter.com/FreeGroup/statuses/978829929 "; XPathDocument doc = new XPathDocument(new StringReader(xml)); XPathNavigator nav = doc.CreateNavigator(); // Compile a standard XPath expression XPathExpression expr; expr = nav.Compile("/rss/channel/item"); XPathNodeIterator iterator = nav.Select(expr); // Iterate on the node set try { while (iterator.MoveNext()) { XPathNavigator nav2 = iterator.Current.Clone(); nav2.MoveToChild("title",""); Console.WriteLine(nav2.Value); nav2.MoveToParent(); nav2.MoveToChild("pubDate",""); Console.WriteLine(nav2.Value); } } catch (Exception ex) { Console.WriteLine(ex.Message); } Console.ReadKey();
这是jan的方法
XmlDocument doc2 = new XmlDocument(); doc2.LoadXml(xml); XmlNode root = doc2.DocumentElement; foreach (XmlNode item in root.SelectNodes(@"/rss/channel/item")) { Console.WriteLine(item.SelectSingleNode("title").FirstChild.Value); Console.WriteLine(item.SelectSingleNode("pubDate").FirstChild.Value); }
替代:
// starts as in Vinko Vrsalovic 's answer // and not including decent eror handling XmlDocument doc = new XmlDocument(new StringReader(xml)); foreach (XmlNode item in doc.SelectNodes(@"/rss/channel/item")) { Console.WriteLine(item.SelectSingleNode("title").Value); Console.WriteLine(item.SelectSingleNode("pubDate").Value); }
我不知道这段代码是慢还是坏练习。 请做评论。
我发现它比使用Navigator和Iterator的另一个更具可读性。
编辑:我使用Xml文档。 像Vinko Vrsalovic的回答中的XPath文档不支持这种工作方式,但速度要快得多: (MSDN)