从XML文档中获取正确的信息

本文关键字:信息 获取 XML 文档 | 更新日期: 2023-09-27 18:11:35

我正在尝试解析这个XML文档:
http://services.tvrage.com/feeds/episode_list.php?sid=3332

我有这样一个类:

public class Episode {
  public int Season { get; set; }
  public string Title { get; set; }
}
我代码:

string path = "http://services.tvrage.com/feeds/episode_list.php?sid=" + id;
XmlDocument doc = new XmlDocument();
doc.Load(path);

现在我被卡住了。如何从该文件创建剧集列表?我很困惑,因为季节使用的属性。

谢谢

从XML文档中获取正确的信息

试试Linq To Xml怎么样?

var xDoc = XDocument.Load("http://services.tvrage.com/feeds/episode_list.php?sid=3332");
var name = xDoc.Root.Element("name").Value;
var episodes = xDoc.Descendants("episode")
                    .Select(e => new
                    {
                        epnum = (string)e.Element("epnum"),
                        //seasonnum = (string)e.Element("seasonnum"),
                        seasonnum = (string)e.Parent.Attribute("no"),
                        prodnum = (string)e.Element("prodnum"),
                        airdate = (string)e.Element("airdate"),
                        link = (string)e.Element("link"),
                        title = (string)e.Element("title"),
                    })
                    .ToList();

试试这个:

var episodes = doc.SelectNodes(@"/Show/Episodelist/Season/episode");
List<Episode> episodesList = new List<Episode>();
foreach (XmlNode episode in episodes)
{
    episodesList.Add(new Episode()
    {
        Season = Int32.Parse(episode.ParentNode.Attributes["no"].Value.ToString()),
        Title = episode.SelectNodes("title")[0].InnerText
    });
}

这里是一个简单的教程,可能会有帮助。它描述了如何从xml文件中获取元素。

之后,您只需要制作一个List<Episode>并填充数据。

string path = @"http://services.tvrage.com/feeds/episode_list.php?sid="+id;
IEnumerable<Episode> Episodes =XDocument.Load(path)
        .Descendants("episode")
        .Select(x => new Episode
        {
            Season = Convert.ToInt16(x.Element("seasonnum").Value),
            Title = x.Element("title").Value
        });