2016-01-13 52 views
0

我想從api中使用公共ip獲取國家,緯度/經度,時區等。xml中的空引用異常 - C#

下面是XML響應我從API獲得,

<IPInformation xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://ws.cdyne.com/"> 
<City>Chennai</City> 
<StateProvince>25</StateProvince> 
<Country>India</Country> 
<Organization/> 
<Latitude>13.0833</Latitude> 
<Longitude>80.28329</Longitude> 
<AreaCode>0</AreaCode> 
<TimeZone/> 
<HasDaylightSavings>false</HasDaylightSavings> 
<Certainty>90</Certainty> 
<RegionName/> 
<CountryCode>IN</CountryCode> 
</IPInformation> 

我加載XML文件中的響應,從那裏用SelectSingleNode我試圖獲得該國的價值。但總是我得到nullreferenceexception

下面是代碼我都試過了,

if (response.StatusCode.ToString().ToLower() == "ok") 
{ 
    XmlDocument xmlDoc = new XmlDocument(); 
    xmlDoc.Load(response.GetResponseStream()); 
    XmlNode msgnode = xmlDoc.DocumentElement.SelectSingleNode("//Country"); -->getting null here 
    string msgname = msgnode.InnerText;          
} 

嘗試下面的一個,

String country = xmlDoc.SelectSingleNode("IPInformation/Country").Value; 

SelectSingleNode總是返回空值

完全stactrace:

at SingleScanPalletTag.MobileClient.ScanOutMenu.GetGeoLocation() 
    at SingleScanPalletTag.MobileClient.ScanOutMenu.button1_Click(Object sender, EventArgs e) 
    at System.Windows.Forms.Control.OnClick(EventArgs e) 
    at System.Windows.Forms.Button.OnClick(EventArgs e) 
    at System.Windows.Forms.ButtonBase.WnProc(WM wm, Int32 wParam, Int32 lParam) 
    at System.Windows.Forms.Control._InternalWnProc(WM wm, Int32 wParam, Int32 lParam) 
    at Microsoft.AGL.Forms.EVL.EnterModalDialog(IntPtr hwnModal) 
    at System.Windows.Forms.Form.ShowDialog() 
    at SingleScanPalletTag.MobileClient.Program.Main() 

enter image description here

任何人都可以告訴我如何從上面的XML獲取國家,經度和緯度值。

請幫幫我。

+0

從你的問題和代碼註釋中不清楚'NullReferenceException'從哪裏拋出。 'SelectSingleNode'行是否會在下一行中引發異常或返回一個'null',導致'NullReferenceException'? – adv12

+0

@ adv12 SelectSingleNode返回空值 – user2681579

+0

請向我們展示完整的堆棧跟蹤。 – etalon11

回答

1

怎麼樣從System.Xml.Linq用戶XDocument()? 假設這個XML文件是不是樹...

XDocument xmlDoc = new XDocument(); 
var sr = new System.IO.StreamReader(response.GetResponseStream()) 
xmlDoc = XDocument.Parse(sr.ReadToEnd()); 

var strCountry = xmlDoc.Root.Element("Country"); 

如果XML有孩子,用xmlDoc.Root.Descendants()

0

如果我有更多的聲譽,我會添加評論指着你這個this StackOverflow article但我不能創建評論,所以它必須是一個答案。

這可能是重複的,所以如果有人可以標記它,請做。

這與名稱空間有關,特別是xmlns="http://ws.cdyne.com/"部分。

創建一個XmlNamespaceManager並添加命名空間。

XmlDocument xmlDoc = new XmlDocument(); 
XmlNamespaceManager namespaces = new XmlNamespaceManager(xmlDoc.NameTable); 
namespaces.AddNamespace("ns", "http://ws.cdyne.com/"); 
xmlDoc.Load(response.GetResponseStream()); 
XmlNode msgnode = xmlDoc.DocumentElement.SelectSingleNode("/ns:IPInformation/ns:Country",namespaces); 
string msgname = msgnode.InnerText; 
+0

@ user2681579如果您發現任何有用的答案,請將它們標記爲答案。 – Exxoff