gpt4 book ai didi

c# - 如何在 c# 中解析 XML 文件(youtube api 结果)?

转载 作者:数据小太阳 更新时间:2023-10-29 02:59:46 25 4
gpt4 key购买 nike

我正在尝试解析从 Youtue API 返回的 XML。 APIcalls 正常工作并创建一个 XmlDocument。我可以获得“entry”标签的 XmlNodeList,但我不确定如何获取其中的元素,例如 , 等...

 XmlDocument xmlDoc = youtubeService.GetSearchResults(search.Term, "published", 1, 50);
XmlNodeList listNodes = xmlDoc.GetElementsByTagName("entry");
foreach (XmlNode node in listNodes)
{
//not sure how to get elements in here
}

此处显示了 XML 文档架构:http://code.google.com/apis/youtube/2.0/developers_guide_protocol_understanding_video_feeds.html

我知道 node.Attributes 是错误的调用,但不确定正确的调用是什么?

顺便说一句,如果有更好的方法(更快、更少的内存)通过序列化或使用 linq 来执行此操作,我很乐意改用它。

感谢您的帮助!

最佳答案

这里有一些读取 XmlDocument 的例子。我不知道什么是最快的或什么需要更少的内存 - 但我更喜欢 Linq To Xml,因为它清晰。

XmlDocument xmlDoc = youtubeService.GetSearchResults(search.Term, "published", 1, 50);
XmlNodeList listNodes = xmlDoc.GetElementsByTagName("entry");
foreach (XmlNode node in listNodes)
{
// get child nodes
foreach (XmlNode childNode in node.ChildNodes)
{
}

// get specific child nodes
XPathNavigator navigator = node.CreateNavigator();
XPathNodeIterator iterator = navigator.Select(/* xpath selector according to the elements/attributes you need */);

while (iterator.MoveNext())
{
// f.e. iterator.Current.GetAttribute(), iterator.Current.Name and iterator.Current.Value available here
}
}

和 linq to xml 之一:

XmlDocument xmlDoc = youtubeService.GetSearchResults(search.Term, "published", 1, 50);
XDocument xDoc = XDocument.Parse(xmlDoc.OuterXml);
var entries = from entry in xDoc.Descendants("entry")
select new
{
Id = entry.Element("id").Value,
Categories = entry.Elements("category").Select(c => c.Value)
};

foreach (var entry in entries)
{
// entry.Id and entry.Categories available here
}

关于c# - 如何在 c# 中解析 XML 文件(youtube api 结果)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1219544/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com