C#Linq to XML无法使用

时间:2011-04-02 21:23:24

标签: c# xml linq linq-to-xml

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看起来像:

<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&region=us">
    <Result>
        <Title>Fosil Fuel | Flickr - Photo Sharing!</Title>
        <Summary>Fosil Fuel ... &lt;a href="http://www.flickr.com/photos/thomashawk/3910488337/" title="Fosil Fuel by Thomas Hawk, on Flickr"&gt;&lt;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>

我做错了什么?每当我尝试一些新的调试器时,我的结果都是空的。

3 个答案:

答案 0 :(得分:1)

您需要指定命名空间:   xmlDoc.Descendants(XName.Get(“Result”,“urn:yahoo:srch”))

您可以稍微简化一下代码:

        var url = "http://search.yahooapis.com/WebSearchService/V1/webSearch?appid=YahooDemo&query=fosil+fuel";
        var request = WebRequest.Create(url);
        using (var response = request.GetResponse())
        {
            // Get the response stream  
            var xmlDoc = XDocument.Load(response.GetResponseStream());
            var results = from q in xmlDoc.Descendants(XName.Get("Result", "urn:yahoo:srch"))
                          select new Resource(
                              q.Element(XName.Get("Title", "urn:yahoo:srch").Value,
                              q.Element(XName.Get("ModificationDate", "urn:yahoo:srch").Value,
                              q.Element(XName.Get("ClickUrl", "urn:yahoo:srch").Value);
            return results.ToList();
        }

答案 1 :(得分:0)

问题是“结果”具有您省略的命名空间“urn:yahoo:srch”。试试xmlDoc.Descendants(XName.Get("Result", "urn:yahoo:srch")),它会起作用

答案 2 :(得分:0)

假设您不需要为WebRequest设置代理或凭据,您可以比Talljoe实际提到的更进一步简化:

string url = "http://search.yahooapis.com/WebSearchService/V1/webSearch?appid=YahooDemo&query=fosil+fuel";
Func<string, XName> qualifiedName = name => XName.Get(name, "urn:yahoo:srch");
XDocument xmlDoc = XDocument.Load(url);
var results = from q in xmlDoc.Descendants(qualifiedName("Result")) 
              select new Resource(
                  q.Element(qualifiedName("ClickUrl")).Value, 
                  q.Element(qualifiedName("Title")).Value, 
                  q.Element(qualifiedName("ModificationDate")).Value); 
return results.ToList();

编辑 - 修复了原始响应中的错误(缺少用于访问元素的XName)并添加了一个时髦的Func<>来重用命名空间限定。适用于我的机器(TM)。