【发布时间】:2010-10-25 15:13:38
【问题描述】:
我可能担心错误的优化,但我有一个唠叨的想法,它一遍又一遍地解析 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);
}
}
}
这是 Good Enough™ 还是有更快的方法来解析我需要的东西?
ps。我在 DownloadStringCompleted 事件中执行大部分操作,我不应该这样做吗?第一次使用这种方法。谢谢!
【问题讨论】: