2017-04-07 156 views
0

我正在製作一個快捷方案,用於我的日常遊戲。這就像手機文件夾一樣工作,以便你知道我的意思。在XML中添加子節點

到目前爲止,我來:

private void addGame(object sender, EventArgs e) 
    { 
     string name  = string.Empty; 
     string game_path = string.Empty; 
     string icon_path = string.Empty; 


     OpenFileDialog ofdGamePath = new OpenFileDialog(); 
     ofdGamePath.Title = "Choose the game..."; 

     OpenFileDialog ofdIconPath = new OpenFileDialog(); 
     ofdIconPath.Title = "Choose the icon..."; 

     if (ofdGamePath.ShowDialog() == DialogResult.OK) 
     { 
      game_path = ofdGamePath.FileName; 
     } 

     if (ofdIconPath.ShowDialog() == DialogResult.OK) 
     { 
      icon_path = ofdIconPath.FileName; 
     } 
    } 

在我目前卡住是保存爲XML路徑。雖然在我的研究中,我發現很多「矯枉過正」的解決方案,這絕對不符合我的範圍。

我games.xml如下所示:

<Games> 
     <game name="" path="" icon="" /> 
    </Games> 

而且讀取該文件也不是問題。下面是我用於閱讀它的代碼:

 XmlDocument xdoc = new XmlDocument(); 
     xdoc.Load(Application.StartupPath + @"\" + args[1]); 
     XmlNodeList elemList = xdoc.GetElementsByTagName("game"); 

     for (int i = 0; i < elemList.Count; i++) 
     { 
      string name = elemList[i].Attributes["name"].Value; 
      string game_path = elemList[i].Attributes["path"].Value; 
      string icon_path = elemList[i].Attributes["icon"].Value; 
     } 

任何人都可以指導我如何簡單地保存一行XML?非常感謝!

回答

0

好吧,我找到了我需要的東西!

 XmlDocument doc = new XmlDocument(); 
     doc.Load(Application.StartupPath + @"\" + args[1]); 
     XmlElement el = (XmlElement)doc.SelectSingleNode("Applications"); 

     if (el != null) 
     { 
      XmlElement elem = doc.CreateElement("app"); 
      elem.SetAttribute("name", "name online game here"); 
      elem.SetAttribute("path", "123123123"); 
      elem.SetAttribute("icon", "test"); 

      el.AppendChild(elem); 
     } 

     doc.Save(Application.StartupPath + @"\" + args[1]); 

,導致:

<app name="name online game here" path="123123123" icon="test" /> 
0
 using (var writer = XmlTextWriter.Create("MyFile.xml"))elemList[i].WriteTo(writer); 
+0

呃。我不認爲你可以跟隨。我想要實現的是將三個字符串保存在一個XML文件中,節點爲,並將其作爲屬性名稱,路徑和圖標(字符串)。 – user2811886

+0

它仍然是相同的答案,但我現在編輯它使用您的元素節點,而之前我使用文檔節點。 –

+0

找到了一個方法。 :) 不管怎麼說,多謝拉! – user2811886