2011-03-28 38 views
0

我在這裏使用的一段代碼幾乎是完美的接受我在做一些我認爲是迭代的錯誤。來自ListView的項目不會成爲XML文件中獨立且不同的節點。每個後續項目都將成爲ListView中第一個項目的子節點。我究竟做錯了什麼?代碼如下:C#:代碼在XML文檔中創建不需要的子節點

private void button1_Click(object sender, EventArgs e) 
    { 
     System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(Application.StartupPath + "\\database.xml", null); 
     writer.WriteStartElement("Database"); 
     for (int i = 0; i < listView1.Items.Count; i++) 
     { 
      writer.WriteStartElement("Account"); 
      writer.WriteAttributeString("Description", listView1.Items[i].SubItems[0].Text); 
      writer.WriteAttributeString("Username", listView1.Items[i].SubItems[1].Text); 
      writer.WriteAttributeString("Password", listView1.Items[i].SubItems[2].Text); 

     } 
     writer.WriteEndElement(); 
     writer.Close(); 
    } 

回答

1

你沒有寫出來的Account末元素 - 這應該這樣做:

for (int i = 0; i < listView1.Items.Count; i++) 
    { 
     writer.WriteStartElement("Account"); 
     writer.WriteAttributeString("Description", listView1.Items[i].SubItems[0].Text); 
     writer.WriteAttributeString("Username", listView1.Items[i].SubItems[1].Text); 
     writer.WriteAttributeString("Password", listView1.Items[i].SubItems[2].Text); 
     writer.WriteEndElement(); 
    } 
1

您不必對writeEndElement你內心的for循環關閉「帳戶節點