关于C#Xml读取

关于C#Xml读取,c#,xml,visual-studio-2010,C#,Xml,Visual Studio 2010,我目前正在做一个XML文件,其中包括城市的“名称”、“地区”、“纬度”和“液化天然气” 这是我的密码: XmlDocument XmlFile = new XmlDocument(); try { XmlFile.Load("..\\..\\liste.xml"); } catch (Exception ex) { Console.WriteLine("Erreur" + ex.Message); }; XmlNodeList MyNodeXML = XmlFile.GetEle

我目前正在做一个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)));
}
ListCoovilles是一个辞典

这是我的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>

有人能帮忙吗?谢谢

XML示例中没有一个节点具有属性,这就是集合中包含
null
元素的原因

尝试将其更改为:

<?xml version="1.0" encoding="UTF-8"?>
<cities>
    <city testAttr = "hello!">
        <name>Abercorn</name>
        <region>Montérégie</region>
        <lat>45.032999</lat>
        <lng>-72.663057</lng>
    </city>
<cities>

阿伯科恩
蒙特雷吉
45.032999
-72.663057

添加
testAttr
应该在
unNode.Attributes
中提供一个有效的集合。您正在使用城市标记中的属性,但我认为您应该使用xml元素。

元素没有属性,只有子元素。属性是与元素处于同一级别的名称=值对。例如

<?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

没有看到任何属性?名称/区域等是元素xml中没有属性,因此总是会出现异常。你应该选择子节点。没有办法像我写XML那样做吗?当然有。。。看看XmlReader类:
    nomVille = unNode.Item["name"].Value
    region = unNode.Item["region"].Value
    lat = unNode.Item["lat"].Value
    lng = unNode.Item["lng"].Value