Getting address data from Google Maps XML

时间:2015-05-04 19:48:35

标签: c# xml xelement

I've extracted some addresses from google maps and they are in an xml file. In myxml file I have some xelements like

<location>, <place_id>, <adr_address>, etc

The 'adr_address' element has different classes and each class contains, city, street, country, etc. values. How do I get each value from the 'adr_address' xElement

<adr_address>&lt;span class="street-address"&gt;1805 Geary Boulevard&lt;/span&gt;, &lt;span class="locality"&gt;San Francisco&lt;/span&gt;, &lt;span class="region"&gt;CA&lt;/span&gt; &lt;span class="postal-code"&gt;94115&lt;/span&gt;, &lt;span class="country-name"&gt;United States&lt;/span&gt;</adr_address>

I'm putting the adr_address xElement in to a object here, but not sure what to do to get the values of each class after that.

XElement firstOrDefault = xElement.Descendants("adr_address").FirstOrDefault();

4 个答案:

答案 0 :(得分:0)

接受的答案是错误的,adr_address没有记录,我们不能依赖它,你必须使用address_components,它是一个数组,所有信息已经拆分并带有类型标识符({ {3}}):

var addrComponents =  xElement.Descendants("address_component");
foreach(var component in addrComponents)
{
   if(component.Descendants('type').Any(t => t.Value == "country"))
       country = component.long_name;
   else if (....)
       ....
}

由于每个组件可能有多种类型,因此您必须在其所有类型中进行搜索,这就是我使用Any的原因。

很抱歉,如果这不能编译,因为我在这里直接写了这个,但这是主要的想法。

答案 1 :(得分:0)

这可行(经过试验和测试):)

// load xml string from webresponse into the linq functionality library .
var elements = XElement.Load(XmlReader.Create(new StringReader(xml)));

// get all the address_component elements in the xml
var addrComponents = elements.Descendants("address_component");

// under those: get all the one's that contain element "type"
var country = addrComponents.Where(d => d.Descendants("type")

// filter further to get the one's with country in their value.(ie. 
//<type>country</type>)
.Any(t => t.Value == "country"))

//first one that matches these criteria, take the long_name value ie 
//<long_name>'merica</long_name> this could be subbed for short_name as well 
//for country code
.First().Element("long_name").Value;

全部完成:)

答案 2 :(得分:0)

如果您不介意使用jQuery,这对我来说非常有用:

var street_address = $("<p>" + place.adr_address + "</p>").find(".street-address").html()

答案 3 :(得分:-1)

我觉得很奇怪,你可以在这种形式下获得地址,邮政编码等价值。通常,Google地图应正确解析这些值。

无论如何,你能做的就是忘记这样的特殊字符:

@echo off
SETLOCAL ENABLEDELAYEDEXPANSION
SET old=*.txt
SET new="c:\Users\user\Desktop\testing.txt"
set counter=0 
(for /f "tokens=*" %%f in ('dir /b %old%') do (
   ren Read the next name from the redirected input file
   set /a counter=counter+1
   for /f "tokens=1* delims=:" %%a in ('findstr /R /N "^" "%new%"^|find "!counter!"') do set "newname=%%b" 
   ren "%%f" "!newname!" 
)

然后使用此正则表达式提取值:

firstOrDefault.Value.Replace("&lt;", "<").Replace("&gt;", ">");