我目前正在做一个XML文件,其中包括城市的"名称","区域","纬度"纬度和"lng".
这是我的代码:
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 version="1.0" encoding="UTF-8"?>
<cities>
  <city name="Abercorn" region="Montérégie" lat="45.032999" lng="-72.663057" />
  <city name="Granby" region="Montérégie" lat="45.4" lng="-72.733333" />
</cites>
嵌套元素(正如您最初所做的那样)和使用属性(如您编写的那样)都是构建XML文档的同等有效方法.
如我所指出的那些元素不是属性.您的代码需要更改为:
    nomVille = unNode.Item["name"].Value
    region = unNode.Item["region"].Value
    lat = unNode.Item["lat"].Value
    lng = unNode.Item["lng"].Value
| 归档时间: | 
 | 
| 查看次数: | 121 次 | 
| 最近记录: |