2017-04-07 71 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