通过XmlReader中的XML元素解析 [英] Parsing through XML elements in XmlReader
本文介绍了通过XmlReader中的XML元素解析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我建设,需要通过一个XML提要运行一个应用程序,但我有与得到的某些元素有点麻烦了。
I'm building an application that needs to run through an XML feed but I'm having a little trouble with getting certain elements.
我使用的 Twitter的饲料,并希望通过所有的<运行;项目>
元素。我可以连接罚款,并从进料的内容,但我无法弄清楚如何选择时,我通过 loopuing只有
项目
元素reader.Read();!
I'm using the Twitter feed and want to run through all the <item>
elements. I can connect fine and get the content from the feed but I can't figure out how to select only the item
elements when I'm loopuing through reader.Read();
.
感谢您的帮助。
推荐答案
要做到这一点,最简单的方法是使用XPath。 。榜样
The easiest way to do that is to use XPath. Example to follow.
string xml = @"<?xml version=""1.0"" encoding=""UTF-8""?>
<rss version=""2.0"">
<channel>
<title>Twitter public timeline</title>
<link>http://twitter.com/public_timeline</link>
<description>Twitter updates from everyone!</description>
<language>en-us</language>
<ttl>40</ttl>
<item>
<title>yasu_kobayashi: rTwT: @junm : yayaya</title>
<description>yasu_kobayashi: rTwT: @junm : yayaya</description>
<pubDate>Tue, 28 Oct 2008 12:04:48 +0000</pubDate>
<guid>http://twitter.com/yasu_kobayashi/statuses/978829930</guid>
<link>http://twitter.com/yasu_kobayashi/statuses/978829930</link>
</item><item>
<title>FreeGroup: WikiFortio - foobar http://tinyurl.com/5gvttf</title>
<description>FreeGroup: WikiFortio - foobar
http://tinyurl.com/5gvttf</description>
<pubDate>Tue, 28 Oct 2008 12:04:47 +0000</pubDate>
<guid>http://twitter.com/FreeGroup/statuses/978829929</guid>
<link>http://twitter.com/FreeGroup/statuses/978829929</link>
</item></channel></rss>
";
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();
这是简的方式工作。
And this is jan's approach working
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);
}
这篇关于通过XmlReader中的XML元素解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文