如何获取下一个 XML 元素值

本文关键字:下一个 XML 元素 获取 何获取 | 更新日期: 2023-09-27 18:22:19

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();

将此代码用于上述 URL (http://feeds.feedburner.com/TechCrunch(,我能够获取所有链接,但我也想获取<<strong>描述>和<<strong>内容:编码>元素值。

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

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

如何获取下一个 XML 元素值

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

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

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

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

不确定,但请尝试.后代和自己((

我建议你使用 XPATh 遍历每个//content/item,然后获取该项目的 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);
    }
  }
}