1

是获取 IP 地址地理位置的免费服务。

我已经构建了一个类函数来获取 xml 响应。这是代码。

    Public Shared Function GetGeoLocation(ByVal IpAddress As String) As String    
        Using client = New WebClient()
            Try
                Dim strFile = client.DownloadString(String.Format("http://freegeoip.net/xml/{0}", IpAddress))

                Dim xml As XDocument = XDocument.Parse(strFile)
                Dim responses = From response In xml.Descendants("Response")
                                Select New With {response.Element("CountryName").Value}
                                Take 1

                Return responses.ElementAt(0).ToString()
            Catch ex As Exception
                Return "Default"
            End Try
        End Using
    End Function

请求请求我没有遇到任何问题。问题是从服务读取返回请求。例如,ip 地址180.73.24.99将返回此值:

<Response>
<Ip>180.73.24.99</Ip>
<CountryCode>MY</CountryCode>
<CountryName>Malaysia</CountryName>
<RegionCode>01</RegionCode>
<RegionName>Johor</RegionName>
<City>Tebrau</City><ZipCode/>
<Latitude>1.532</Latitude>
<Longitude>103.7549</Longitude>
<MetroCode/>
<AreaCode/>
</Response>

我的功能GetGeoLocation(180.73.24.99)将返回{ Value = Malaysia }。如何将此功能修复为仅返回Malaysia. 我猜我的 linq 语句有问题。

解决方案

Dim responses = From response In xml.Descendants("Response")
                Select response.Element("CountryName").Value
4

1 回答 1

1

无需返回此Select New With {response.Element("CountryName").Value}匿名对象,只需返回CountryName元素的值:

Select response.Element("CountryName").Value

另外我建议您使用FirstOrDefault而不是使用第一项。

Dim xdoc = XDocument.Parse(strFile)
Dim countries = From r In xdoc...<Response>
                Select r.<CountryName>.Value
Return If(countries.FirstOrDefault(), "Default")

甚至在一行中

Return If(xdoc...<Response>.<CountryName>.FirstOrDefault(), "Default")
于 2013-06-06T13:51:45.627 回答