C# Linq to XML 无法使用

发布于 2024-10-29 01:40:34 字数 2569 浏览 7 评论 0原文

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));
       }
}

yahoo 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>

我做错了什么?每次我尝试新的东西时,调试器都会显示我的结果是空的。

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));
       }
}

The yahoo xml looks like:

<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>

What am I doing wrong? Everytime I try something new the debugger shos that my results are empty.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

秋日私语 2024-11-05 01:40:34

您需要指定一个命名空间:
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();
        }

You need to specify a namespace:
xmlDoc.Descendants(XName.Get("Result", "urn:yahoo:srch"))

You can simplify your code a bit:

        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();
        }
别想她 2024-11-05 01:40:34

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

Problem is that "Result" has namespace "urn:yahoo:srch" that you are omitting. Try xmlDoc.Descendants(XName.Get("Result", "urn:yahoo:srch")) and it will work

北斗星光 2024-11-05 01:40:34

假设您不需要为 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)。

Assuming you don't need to set up proxies or credentials for the WebRequest you can simplify even further than Talljoe mentioned actually:

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();

EDIT - fixed bug in my original response (missing XName for accessing elements) and added a funky Func<> to make reuse of namespace qualification. Works on my machine(TM).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文