簡體   English   中英

C#無法讀取XML數組及其中的節點

[英]C# Can't read a XML Array and the Nodes within

我正在嘗試閱讀以下回復。 綠線表示我需要讀取的節點

我需要始終閱讀第三個“結果”項

在此處輸入圖片說明

我的代碼:

            string location = "";

            string url = "http://maps.googleapis.com/maps/api/geocode/xml?" + latitude + "," + longitude + "&sensor=true";

            XmlDocument doc1 = new XmlDocument();
            doc1.Load(url);
            XmlElement root = doc1.DocumentElement;
            XmlNodeList nodes = root.SelectNodes("/GeocodeResponse[0]");


            foreach (XmlNode node in nodes)
            {
                location = node["formatted_address"].InnerText;
            }

該代碼實際上沒有給我任何節點,而節點數為0。我在做什么錯?

問題出在Xpath表達式中。 要獲取所有其他結果節點,請使用以下命令:

XmlNodeList nodes = root.SelectNodes("/GeocodeResponse/result");

如果只需要第三個結果節點,則可以使用SelectSingleNode方法:

var node = root.SelectSingleNode("/GeocodeResponse/result[3]");
location = node["formatted_address"].InnerText;

更新資料

最初的問題出在您的網址中。您忘記了latlng=部分。 這是工作網址的示例:

https://maps.googleapis.com/maps/api/geocode/xml?latlng=40.714224,-73.961452&sensor=true

如果您的系統屬性具有,該數字格式也可能存在問題,它是雙倍數。 您可以使用InvariantCulture解決此問題。 因此,工作示例將是:

double latitude = 40.714224;
double longitude = -73.961452;
string url = String.Format(System.Globalization.CultureInfo.InvariantCulture,
    "http://maps.googleapis.com/maps/api/geocode/xml?latlng={0},{1}&sensor=true", 
    latitude, 
    longitude);
XmlDocument doc = new XmlDocument();
doc.Load(url);
XmlElement root = doc.DocumentElement;
var node = root.SelectSingleNode("/GeocodeResponse/result[3]");
var location = node["formatted_address"].InnerText;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM