2013-05-19 43 views
0

在XML本網站http://geoiptool.com/data.php報告數據獲取XML單數據

<markers> 
    <marker lat="xxx" lng="xxx" city="xxx" 
     country="xxx" host="xxx" ip="xx" code="xx"/> 
</markers> 

是有可能得到緯度,經度,城市和國家?我嘗試這樣做:

XmlDocument doc = new XmlDocument(); 
doc.Load("http://geoiptool.com/data.php"); 
string xmlcontents = doc.InnerXml; 

但返回所有XML數據

+0

嘗試doc.Load( 「http://geoiptool.com/data.php」).Descendants( 「標記」) .Attributes( 「LAT」) –

+0

不起作用此代碼=( – Federal09

+0

@TamilSelvan ,'doc.Load'返回void。你需要將你的代碼分解成兩條語句。 – gunr2171

回答

2

一旦你得到你正在尋找(標記)的節點,你可以從中攫取的屬性。請注意,在從屬性中訪問屬性之前檢查屬性是否爲空通常是一個好主意。這是獲得LAT屬性的一個示例:

XmlDocument doc = new XmlDocument(); 
    doc.Load("http://geoiptool.com/data.php"); 

    var marker = doc.SelectSingleNode("//markers/marker"); 
    string lat = marker.Attributes["lat"].Value; 
+0

非常感謝,它完美的工作 – Federal09

2

(代替XmlDocument)另一種選擇是使用XElement。這允許使用Linq,這使得一切都變得更好。

XElement root = XElement.Load("http://geoiptool.com/data.php"); //check me on that, not sure if it will handle urls 
foreach(var marker in root.Elements("marker")) 
{ 
    string lat = marker.Attribute("lat").Value; 
    string lng = marker.Attribute("lng").Value; 
    ... 
}