【发布时间】:2016-01-13 17:42:47
【问题描述】:
我正在尝试使用公共 ip 从 api 获取国家、纬度/经度、时区等。
下面是我从 api 得到的 xml 响应,
<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 总是返回一个空值
完整的sacttrace:
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()
谁能告诉我如何从上面的xml中获取国家,纬度和经度值。
请帮帮我。
【问题讨论】:
-
从您的问题和代码 cmets 中不清楚
NullReferenceException是从哪里抛出的。SelectSingleNode行是否抛出异常或返回null导致下一行出现NullReferenceException? -
@adv12 SelectSingleNode 返回一个空值
-
请向我们展示完整的堆栈跟踪。
-
@etalon11 添加了有问题的完整堆栈跟踪
-
县不是节点。这是一个简单的元素。您甚至可以将 XML 序列化为一个对象。我个人更喜欢这种方式。因此,如果您的 XML 始终具有相同的结构,您可以创建一个该类型的类并创建一个具有序列化的对象。
标签: c# .net xml visual-studio-2010