因此,我尝试从此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;
答案 0 :(得分:0)
使用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; }
}
}