c# - 从 xml 检索数据的问题
问题描述
所以我试图从这个 xml 文件中检索订阅者计数,但我在获取数据时遇到了问题。目前我在每个级别都使用 doc.DocumentElement.SelectSingleNode 但我运气不佳,而且由于我对 C# xml 不太熟悉,所以我真的不知道我的问题是什么。任何帮助将不胜感激,xml附在下面。
我正在尝试从subscriberCount 获取数据,并且我当前的代码附在底部,尽管它不起作用
-最大限度
<?xml version="1.0" encoding="UTF-8"?>
<Root>
<kind>youtube#channelListResponse</kind>
<etag>"xxx"</etag>
<pageInfo>
<totalResults>1</totalResults>
<resultsPerPage>1</resultsPerPage>
</pageInfo>
<items>
<kind>youtube#channel</kind>
<etag>"xxx"</etag>
<id>xxx</id>
<statistics>
<viewCount>0</viewCount>
<commentCount>0</commentCount>
<subscriberCount>200</subscriberCount>
<hiddenSubscriberCount>false</hiddenSubscriberCount>
<videoCount>5</videoCount>
</statistics>
</items>
</Root>
string totalSubs = doc.DocumentElement.SelectSingleNode("Root").SelectSingleNode("items").SelectSingleNode("statistics").SelectSingleNode("subscriberCount").Value;
解决方案
使用 xml linq:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = @"c:\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
XElement root = doc.Root;
Response response = new Response();
response.kind = (string)root.Element("kind");
response.etag = (string)root.Element("etag");
response.totalResults = (int)root.Descendants("totalResults").FirstOrDefault();
response.resultsPerPage = (int)root.Descendants("resultsPerPage").FirstOrDefault();
XElement items = root.Element("items");
response.itemKind = (string)items.Element("kind");
response.itemEtag = (string)items.Element("etag");
response.id = (string)items.Element("id");
XElement statistics = items.Element("statistics");
response.viewCount = (int)statistics.Element("viewCount");
response.commentCount = (int)statistics.Element("commentCount");
response.subscriberCount = (int)statistics.Element("subscriberCount");
response.hiddenSubscriberCount = (Boolean)statistics.Element("hiddenSubscriberCount");
response.videoCount = (int)statistics.Element("videoCount");
}
}
public class Response
{
public string kind { get; set; }
public string etag { get; set; }
public int totalResults { get; set; }
public int resultsPerPage { get; set; }
public string itemKind { get; set; }
public string itemEtag { get; set; }
public string id { get; set; }
public int viewCount { get; set; }
public int commentCount { get; set; }
public int subscriberCount { get; set; }
public Boolean hiddenSubscriberCount { get; set; }
public int videoCount { get; set; }
}
}
推荐阅读
- vue.js - vuejs 传递数据-* 属性 + 文本
- amazon-web-services - 有没有办法找出 AWS Lambda 中存在的函数数量?
- python - 为什么 re.group 函数没有给我预期的输出
- javascript - 打开外部链接时如何在 pwa 中隐藏导航栏
- python-3.x - 无法将 ttk 主题应用于 .toplevel()
- recaptcha - ReCAPTCHA 自动提交,没有提交按钮
- javascript - selectric js 与 Ctrl + 单击
- c++ - std::array 的项目无意中脱离上下文而更改
- angular - 从 Fullcalendar 资源时间线中删除世界“Uhr”
- android - 一位信号颤动用户订阅失败错误