string url = "http://search.yahooapis.com/WebSearchService/V1/webSearch?appid=YahooDemo&query=fosil+fuel";
List<Resource> sites = new List<Resource>();
WebRequest request = WebRequest.Create(url);
using (WebResponse response = request.GetResponse())
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
XDocument xmlDoc = new XDocument();
xmlDoc = XDocument.Parse(reader.ReadToEnd());
var results = from q in xmlDoc.Descendants("Result")
select new
{
Url = q.Element("ClickUrl").Value,
Title = q.Element("Title").Value,
Date = q.Element("ModificationDate").Value,
};
foreach (var item in results)
{
sites.Add(new Resource(item.Title, item.Date, item.Url));
}
}
雅虎的XML的样子:C#的LINQ to XML中是与
<ResultSet xsi:schemaLocation="urn:yahoo:srch http://api.search.yahoo.com/WebSearchService/V1/WebSearchResponse.xsd" type="web" totalResultsAvailable="134000" totalResultsReturned="10" firstResultPosition="1" moreSearch="/WebSearchService/V1/webSearch?query=fosil+fuel&appid=YahooDemo®ion=us">
<Result>
<Title>Fosil Fuel | Flickr - Photo Sharing!</Title>
<Summary>Fosil Fuel ... <a href="http://www.flickr.com/photos/thomashawk/3910488337/" title="Fosil Fuel by Thomas Hawk, on Flickr"><img src="http://farm3.static.flickr. ...</Summary>
<Url>http://www.flickr.com/photos/thomashawk/3910488337/</Url>
<ClickUrl>http://www.flickr.com/photos/thomashawk/3910488337/</ClickUrl>
<DisplayUrl>www.flickr.com/photos/thomashawk/3910488337/</DisplayUrl>
<ModificationDate>1298707200</ModificationDate>
<MimeType>text/html</MimeType>
<Cache>
<Url>http://uk.wrs.yahoo.com/_ylt=A0WTeekRk5dNbBEAx4zdmMwF;_ylu=X3oDMTBwZTdwbWtkBGNvbG8DZQRwb3MDMQRzZWMDc3IEdnRpZAM-/SIG=16k5dp83c/EXP=1301865617/**http%3A//66.218.69.11/search/cache%3Fei=UTF-8%26appid=YahooDemo%26query=fosil%2Bfuel%26u=www.flickr.com/photos/thomashawk/3910488337/%26w=fosil%2Bfuel%2Bfuels%26d=V6aQZ_bJWYzN%26icp=1%26.intl=us</Url>
<Size>119332</Size>
</Cache>
</Result>
</ResultSet>
我在做什么错?每次我尝试新的东西时,调试器都会提示我的结果是空的。
我试过这个以及为下面的每个元素设置XName。然而,它不断从linq查询中获取null .... – Jarod 2011-04-03 03:46:41
我复制了你的代码并运行它。添加命名空间给了我结果。 https://gist.github.com/900198 – Talljoe 2011-04-03 04:52:56