2010-07-04 66 views
1

图片刮XML时,我有这样的XML:获取错误信息的LINQ

<ipb> 
    <profile> 
     <id>335389</id> 
     <name>stapia.gutierrez</name> 
     <rating>0</rating> 
    </profile> 
</ipb> 

我试图让ID,名称和等级。任何指导?

这里是我有什么,我得到:

public User FindInformation() 
{ 
    string xml = new WebClient().DownloadString(String.Format("http://www.dreamincode.net/forums/xml.php?showuser={0}", userID)); 
    XDocument doc = XDocument.Parse(xml); 

    var id = from u in doc.Descendants("profile") 
       select (string)u.Element("id"); 

    var name = from u in doc.Descendants("profile") 
       select (string)u.Element("name"); 

    var rating = from u in doc.Descendants("profile") 
       select (string)u.Element("rating"); 

    User user = new User(); 
    user.ID = id.ToString(); 
    user.Name = name.ToString(); 
    user.Rating = rating.ToString(); 

    return user; 
} 

这是我在我的文本框用于测试目的得到。

System.Linq.Enumerable+WhereSelectEnumerableIterator`2[System.Xml.Linq.XElement,System.String] System.Linq.Enumerable+WhereSelectEnumerableIterator`2[System.Xml.Linq.XElement,System.String] System.Linq.Enumerable+WhereSelectEnumerableIterator`2[System.Xml.Linq.XElement,System.String] 

回答

1

你需要提取的<profile>一个实例,然后在该操作:

XDocument doc = XDocument.Parse(xml); 

foreach(var profile in doc.Descendants("profile")) 
{ 
    var id = profile.Element("id").Value; 
    var name = profile.Element("name").Value; 
    var rating = profile.Element("rating").Value; 

    User user = new User(); 
    user.ID = id; 
    user.Name = name; 
    user.Rating = rating; 
} 

你现在正在做的是选择(doc.Descendants("profile")节点列表将返回节点列表,可能只有一个元素 - 但仍然是一个列表),然后是该列表中的所有“id”元素....不是我想要的!

+0

谢谢,这正是我所需要的。还没有用过很多XML。 :] – 2010-07-04 19:24:15

+0

别担心我总是这样做。计时器有8分钟才能接受。 – 2010-07-04 19:50:21

+0

系统需要一段时间才能通过aswer标记回答。不要跳枪。 – 2010-07-04 19:50:35

0
var id = from u in doc.Descendants("profile") 
select (string)u.Element("id"); 

这&等之类的语句,这些将返回一个枚举&不是一个具体的实例。 即发生什么事,如果你的XML有许多节点满足条件?因此,如果您希望获得第一个项目(或者如果您的xml结构完全如上所示,并且没有额外的节点),则拨打FirstFirstOrDefault应该有所帮助。