0

我正在尝试从下面给出的 xml 文档中获取位置名称值,但它显示了 argumentnullexception 。任何帮助将不胜感激

    <Response xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"     xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://schemas.microsoft.com/search/local/ws/rest/v1">
  <Copyright>
Copyright © 2011 Microsoft and its suppliers. All rights reserved. This API cannot be accessed and the content and any results may not be used, reproduced or transmitted in any manner without express written permission from Microsoft Corporation.
  </Copyright>
  <BrandLogoUri>
http://dev.virtualearth.net/Branding/logo_powered_by.png
  </BrandLogoUri>
  <StatusCode>200</StatusCode>
  <StatusDescription>OK</StatusDescription>
  <AuthenticationResultCode>ValidCredentials</AuthenticationResultCode>
  <TraceId>
dd31ffaf098f4406b7ecdd0da36680ff
  </TraceId>
      <ResourceSets>
    <ResourceSet>
      <EstimatedTotal>1</EstimatedTotal>
      <Resources>
        <Location>
          <Name>1 Microsoft Way, Redmond, WA 98052</Name>
          <Point>
            <Latitude>47.640568390488625</Latitude>
            <Longitude>-122.1293731033802</Longitude>
          </Point>....

这是我试过的

void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
    {

        XDocument result = XDocument.Parse(e.Result);
        var ns = result.Root.GetDefaultNamespace();
        var address1 = from query in result.Descendants(ns + "Location")
                      select new Location
                      {
                          address = (string)query.Element(ns + "Name")
                      };
        Location loc = new Location();
        MessageBox.Show(loc.address);

    }
4

2 回答 2

0

问题是你正在取回一个集合(它有一个 Location 对象),然后不使用它。

尝试这个:

Location loc = result.Descendants(ns1 + "Location")
                     .Select(x => new Location { address = (string)x.Element(ns1 + "Name") })
                     .First(); // This gets you a single item
MessageBox.Show(loc.address);

或者,如果您可能有多个回报,那么您可以迭代:

var locs = result.Descendants(ns1 + "Location")
                     .Select(x => new Location { address = (string)x.Element(ns1 + "Name") });
foreach(var loc in locs)
    MessageBox.Show(loc.address);

(我确认这在我刚刚运行时有效 - 如果这对您不起作用,请准确说明您遇到的问题)。

于 2013-05-18T18:33:49.650 回答
0

除了这个,我看不出你的代码有什么问题:

Location loc = new Location();
MessageBox.Show(loc.address);

您正在制作一个新对象并尝试显示loc.address?当然你会得到ArgumentNullException

address1 已经保存了 xml 的结果,但您正在创建一个新对象。

尝试这个:

首先删除这一行:

Location loc = new Location();

然后添加这个:

foreach (var address in address1) {
    MessageBox.Show(address.address);
}

ps 下一次,重要的是在您的问题中显示哪一行引发了异常,以便人们可以看到问题出在哪里。

于 2013-05-18T18:55:17.760 回答