2016-01-13 49 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