如何获取下一个XML Element值?

时间:2012-02-03 16:06:10

标签: c# asp.net xml linq xml-parsing

XDocument coordinates = XDocument.Load("http://feeds.feedburner.com/TechCrunch");
System.IO.StreamWriter StreamWriter1 = new System.IO.StreamWriter(DestFilePath);

foreach (var coordinate in coordinates.Descendants("guid"))
                {
                    string Links = coordinate.Value;                 
                    StreamWriter1.WriteLine(Links + Environment.NewLine );
                }

StreamWriter1.Close();

将此代码用于上述网址(http://feeds.feedburner.com/TechCrunch)我可以获取所有链接,但我还想获得< description >和< 内容:已编码>元素值。

问题在于我想获得< description >等值及其 guid 值,以便我可以将它们串行存储(在数据库中)。

我应该为此目的使用 LINQ 吗? 但请问怎么说?

4 个答案:

答案 0 :(得分:2)

您应该遍历每个“项目”并检索其属性。不要忘记“内容”命名空间。

  XNamespace nsContent = "http://purl.org/rss/1.0/modules/content/";
  XDocument coordinates = XDocument.Load("http://feeds.feedburner.com/TechCrunch");

  foreach (var item in coordinates.Descendants("item"))
  {
          string link = item.Element("guid").Value;
          string description = item.Element("description").Value;
          string content = item.Element(nsContent + "encoded").Value;

  }

答案 1 :(得分:0)

一种方法是你可以尝试单独枚举它们,

foreach (var coordinate in coordinates.Descendants())
    {
    foreach (var element in coordinate.Elements("description"))
    {
            string Links = element.Value;                 
            StreamWriter1.WriteLine(Links + Environment.NewLine );
    }
            foreach (var element in coordinate.Elements("guid"))
    {
            string Links = element.Value;                 
            StreamWriter1.WriteLine(Links + Environment.NewLine );
    }   
    //.................         
    }

答案 2 :(得分:0)

不确定但是尝试.DescendantsAndSelf()

答案 3 :(得分:0)

我建议您使用XPATh迭代每个//内容/项目,然后获取该项目的guid,内容等。

using System;
using System.Net;
using System.Xml;

namespace TechCrunch
{
  class Program
  {
    public static void Main(string[] args)
    {
      Console.WriteLine("Hello World!");

      try
      {
        HttpWebRequest request = HttpWebRequest.CreateHttp(
          "http://feeds.feedburner.com/TechCrunch");
        WebResponse response = request.GetResponse();

        XmlDocument feedXml = new XmlDocument();
        feedXml.Load(response.GetResponseStream());

        XmlNodeList itemList = feedXml.SelectNodes("//channel/item");
        Console.WriteLine("Found " + itemList.Count + " items.");

        foreach(XmlNode item in itemList)
        {
          foreach(XmlNode child in item.ChildNodes)
          {
            Console.WriteLine("There is a child named " + child.Name);
          }
        }
      }
      catch(Exception ex)
      {
        Console.WriteLine(ex.ToString());
      }

      Console.Write("Press any key to continue . . . ");
      Console.ReadKey(true);
    }
  }
}