C# 在 XmlReader 中解析 XML 元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/243022/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 19:32:44  来源:igfitidea点击:

Parsing through XML elements in XmlReader

c#xmlreader

提问by Ross

I'm building an application that needs to run through an XML feed but I'm having a little trouble with getting certain elements.

我正在构建一个需要通过 XML 提要运行的应用程序,但在获取某些元素时遇到了一些麻烦。

I'm using the Twitter feedand 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 itemelements when I'm loopuing through reader.Read();.

我正在使用Twitter 提要并希望浏览所有<item>元素。我可以正常连接并从提要中获取内容,但我无法弄清楚如何item在循环时只选择元素reader.Read();

Thanks for your help!

谢谢你的帮助!

采纳答案by Vinko Vrsalovic

The easiest way to do that is to use XPath. Example to follow.

最简单的方法是使用 XPath。要遵循的例子。

 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

这是 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);
        }

回答by jan

An alternative:

替代:

// 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);
}

I don't know if this code is slower or bad practice. Please do comment.

我不知道这段代码是较慢还是不好的做法。请做评论。

I find it more readable than the other one using Navigator and Iterator.

我发现它比使用 Navigator 和 Iterator 的另一个更具可读性。

Edit:I use an XmlDocument. An XPathDocument as in Vinko Vrsalovic 's answer doesn't support this way of working, but is a lot faster: (MSDN)

编辑:我使用Xml文档。Vinko Vrsalovic 的回答中的XPath文档不支持这种工作方式,但速度要快得多: (MSDN)