我可能担心错误的优化,但我有一个挥之不去的想法,它一遍又一遍地解析 xml 树,也许我在某个地方读过它。不记得了。
无论如何,这就是我正在做的事情:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.Net;
namespace LinqTestingGrounds
{
class Program
{
static void Main(string[] args)
{
WebClient webClient = new WebClient();
webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClient_DownloadStringCompleted);
webClient.DownloadStringAsync(new Uri("http://www.dreamincode.net/forums/xml.php?showuser=335389"));
Console.ReadLine();
}
static void webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error != null)
{
return;
}
XDocument xml = XDocument.Parse(e.Result);
User user = new User();
user.ID = xml.Element("ipb").Element("profile").Element("id").Value;
user.Name = xml.Element("ipb").Element("profile").Element("name").Value;
user.Rating = xml.Element("ipb").Element("profile").Element("rating").Value;
user.Photo = xml.Element("ipb").Element("profile").Element("photo").Value;
user.Reputation = xml.Element("ipb").Element("profile").Element("reputation").Value;
user.Group = xml.Element("ipb").Element("profile").Element("group").Element("span").Value;
user.Posts = xml.Element("ipb").Element("profile").Element("posts").Value;
user.PostsPerDay = xml.Element("ipb").Element("profile").Element("postsperday").Value;
user.JoinDate = xml.Element("ipb").Element("profile").Element("joined").Value;
user.ProfileViews = xml.Element("ipb").Element("profile").Element("views").Value;
user.LastActive = xml.Element("ipb").Element("profile").Element("lastactive").Value;
user.Location = xml.Element("ipb").Element("profile").Element("location").Value;
user.Title = xml.Element("ipb").Element("profile").Element("title").Value;
user.Age = xml.Element("ipb").Element("profile").Element("age").Value;
user.Birthday= xml.Element("ipb").Element("profile").Element("birthday").Value;
user.Gender = xml.Element("ipb").Element("profile").Element("gender").Element("gender").Element("value").Value;
Console.WriteLine(user.ID);
Console.WriteLine(user.Name);
Console.WriteLine(user.Rating);
Console.WriteLine(user.Photo);
Console.WriteLine(user.Reputation);
Console.WriteLine(user.Group);
Console.WriteLine(user.Posts);
Console.WriteLine(user.PostsPerDay);
Console.WriteLine(user.JoinDate);
Console.WriteLine(user.ProfileViews);
Console.WriteLine(user.LastActive);
Console.WriteLine(user.Location);
Console.WriteLine(user.Title);
Console.WriteLine(user.Age);
Console.WriteLine(user.Birthday);
Console.WriteLine(user.Gender);
//Console.WriteLine(xml);
}
}
}
这足够好™还是有更快的方法来解析我需要的东西?
附注我正在 DownloadStringCompleted 事件中执行大部分操作,我不应该这样做吗?第一次使用这个方法。谢谢!
不知道效率,但为了可读性使用profile
变量而不是一遍又一遍地遍历整个事物:
User user = new User();
var profile = xml.Element("ipb").Element("profile");
user.ID = profile.Element("id").Value;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)