我目前正在做一个XML文件,其中包括城市的“名称”,“地区”,“经纬度”和“lng”。关于C#Xml读取
这里是我的代码:
XmlDocument XmlFile = new XmlDocument();
try {
XmlFile.Load("..\\..\\liste.xml");
}
catch (Exception ex)
{
Console.WriteLine("Erreur" + ex.Message);
};
XmlNodeList MyNodeXML = XmlFile.GetElementsByTagName("city");
foreach (XmlNode unNode in MyNodeXML)
{
string nomVille = unNode.Attributes[0].Value;
string lat = unNode.Attributes[1].Value;
string lng = unNode.Attributes[2].Value;
listeCooVilles.Add(nomVille, new PointF(float.Parse(lat), float.Parse(lng)));
}
凡listeCooVilles是Dictionnary。
这里是我的XML:我做了一个样本测试:
<?xml version="1.0" encoding="UTF-8"?>
<cities>
<city>
<name>Abercorn</name>
<region>Montérégie</region>
<lat>45.032999</lat>
<lng>-72.663057</lng>
</city>
<cities>
我看到很多帖子做了与上述相同的StackOverflow的,但是我还是上线的IndexOutOfRange异常
string nomVille = unNode.Attributes[0].Value;
有人可以帮忙吗?谢谢!
看不到任何属性?名称/区域等是元素 –
你的xml中没有属性,所以你总是会得到一个异常。你应该去找孩子的节点。 – Peter