首页 > 解决方案 > 阅读 Open Street Map xml 响应

问题描述

尝试从 Open Street Map 网页读取数据。我有经度和纬度。基于这些网页链接生成。

假设输出是: https://nominatim.openstreetmap.org/reverse?format=xml&lat=48.927834&lon=16.861641&zoom=18&addressdetails=1

如何阅读网页内容?我已经尝试过了,但我没有得到任何东西result

  string urlString = "https://nominatim.openstreetmap.org/reverse?format=xml&lat=48.927834&lon=16.861641&zoom=18&addressdetails=1";

  HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(urlString);
  myRequest.Method = "GET";
  WebResponse myResponse = myRequest.GetResponse();
  StreamReader sr = new StreamReader(myResponse.GetResponseStream(), System.Text.Encoding.UTF8);
  string result = sr.ReadToEnd();
  sr.Close();
  myResponse.Close();

得到:

抛出的异常:System.Net.Requests.dll 中的“System.Net.WebException”抛出的异常:System.Private.CoreLib.dll 中的“System.Net.WebException”

在此处输入图像描述

我的目标是解析 xml:

  // Loading from a file, you can also load from a stream
  XDocument xml = XDocument.Parse(result);

  // Query the data and write out a subset of contacts
  IEnumerable<string> query = from c in xml.Root.Descendants("addressparts")
              select c.Element("road").Value + " " +
                     c.Element("house_number").Value;

标签: c#xmlxml-parsingxmlhttprequestopenstreetmap

解决方案


您必须在请求中提供有效的用户代理,否则请求将被阻止。根据当前的Nominatim 使用政策

  • 提供一个有效的 HTTP Referer 或User-Agent来标识应用程序(由 http 库设置的普通用户代理不会这样做)。
myRequest.UserAgent = "MyApp Version 1.2.3.4"

推荐阅读