简体   繁体   English

无法使用LINQ从Google Geocoding API XML输出获取address_component元素

[英]Can not get address_component element from Google Geocoding API XML output with LINQ

I try to get some data from Google Geocoding API with C# and ASP.net. 我尝试使用C#和ASP.net从Google Geocoding API获取一些数据。 But I have trouble with XML responce. 但是我在XML响应方面遇到麻烦。 I get valid XML and I can get evry element besides "address_component" element. 我得到有效的XML,并且除了“ address_component”元素外,还可以得到evry元素。 (XML looks like this : http://maps.googleapis.com/... ) (XML看起来像这样: http://maps.googleapis.com / ...

    /* data is a string with XML from Google server */            
    XDocument receivedXml = new XDocument();
    receivedXml = XDocument.Parse(data);
    XName address = XName.Get("address_component");

    var root = reciviedXml.Root;              //returns corect XElement
    XElement result = root.Element("result"); //returns corect XElement
    IEnumerable<XElement> components = result.Elements("address_component"); //returns empty collection

This is another way, I'have tried it to with the same result. 这是另一种方式,我已经尝试了相同的结果。

    var results = reciviedXml.Descendants("address_component");

And when I try to get some descendant of like: 当我尝试获得类似的后代时:

    var types = receivedXml.Descendants("type");

It's the empty collection to. 这是空集合。 But another elements in "result" tag (like the "location" tag)I can get successfully. 但是“结果”标签中的另一个元素(例如“位置”标签)可以成功实现。

Thanks for any advice. 感谢您的任何建议。

The following: 下列:

var receivedXml = XDocument.Load("http://maps.googleapis.com/maps/api/geocode/xml?latlng=49.1962253,16.6071422&sensor=false");
Console.WriteLine(receivedXml.Root.Element("result").Elements("address_component").Count());
Console.WriteLine(receivedXml.Descendants("address_component").Count());

Writes 10 and 28 respectively. 分别写入10和28。 Make sure you are using the same instance - in your question you usereceivedXml as well as reciviedXml so you may have two instances XDocument and one of these may contain different data. 确保您使用的是同一实例-在问题中,您同时收到了usereceivedXml和reciviedXml,因此您可能有两个实例XDocument,其中一个实例可能包含不同的数据。 Also you don't need to instantiate XDocument as XDocument.Parse() will do it for you (and the address variable seems to be unused) 另外,您也不需要实例化XDocument,因为XDocument.Parse()会为您完成(地址变量似乎未使用)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM