2011-12-01 57 views
0

我目前正在做一個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; 

有人可以幫忙嗎?謝謝!

+0

看不到任何屬性?名稱/區域等是元素 –

+0

你的xml中沒有屬性,所以你總是會得到一個異常。你應該去找孩子的節點。 – Peter

回答

5

元素沒有屬性 - 只有子元素。屬性是與元素相同級別的名稱=值對。例如。

<?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文檔都同樣有效的方式。

+0

有沒有辦法像我寫XML一樣? – user1076263

+0

當然有......看看XmlReader類:http://msdn.microsoft.com/en-us/library/cc189056(v=vs.95).aspx – Josh

3

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> 

加入了testAttr應在unNode.Attributes提供有效的集合。

+0

感謝您的評論:我試過了,但它仍然會拋出異常。 – user1076263

2

您在城市標記中使用的屬性,但我認爲你應該使用XML元素。

5

正如我們所指出的,那些元素不是屬性。您的代碼需要更改爲:

nomVille = unNode.Item["name"].Value 
    region = unNode.Item["region"].Value 
    lat = unNode.Item["lat"].Value 
    lng = unNode.Item["lng"].Value