Reputation: 213
I have an xml file t hat I'm gonna delete 1 node from... And here is it:
<games>
<game>
<gameName>Test6</gameName>
<exePath>E:\LeagueOfLegends\League of Legends\lol.launcher.exe</exePath>
<Files>
<file>C:\Users\Stian\Desktop\toComp\334.jpg</file>
<file>C:\Users\Stian\Desktop\toComp\341.jpg</file>
<file>C:\Users\Stian\Desktop\toComp\compressed\334.jpg</file>
<file>C:\Users\Stian\Desktop\toComp\compressed\341.jpg</file>
<file>C:\Users\Stian\Desktop\toComp\compressed\Test1\334.jpg</file>
<file>C:\Users\Stian\Desktop\toComp\compressed\Test1\341.jpg</file>
</Files>
</game>
</games>
And my problem is... I want to delete one of the file nodes... That contains "C:\Users\Stian\Desktop\toComp\334.jpg" as inner text...
And my code for that is at the moment(And it's not working):
private void removeFile_Click(object sender, EventArgs e)
{
String appDataFolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData).ToString();
String gpsPath = appDataFolder + "/GameProfileSaver";
String gName = comboBox1.SelectedItem.ToString();
XmlDocument doc = new XmlDocument();
doc.Load(gpsPath + "/games.xml");
foreach (string li in listBox1.SelectedItems)
{
string liS = li.Replace(@"\\", @"\");
XmlNode file = doc.SelectSingleNode("games/game[gameName='" + gName + "']/Files[@file='" + liS + "']");
file.ParentNode.RemoveChild(file);
}
doc.Save(gpsPath + "/games.xml");
}
And I'm just getting a NullReferenceException.... And when I tried something else.. That I don't have the code for now.. Is that it deleted the whole node...
Upvotes: 0
Views: 42
Reputation: 116178
How about using Linq2Xml?
string nodeToDelete = @"C:\Users\Stian\Desktop\toComp\334.jpg";
var xDoc = XDocument.Load(fname);
xDoc.Descendants()
.First(n => (string)n == nodeToDelete)
.Remove();
string newXml = xDoc.ToString();
Upvotes: 1
Reputation: 5343
XmlNode file = doc.SelectSingleNode("games/game[gameName='" + gName + "']/Files/file['" + liS + "']");
works for me
Upvotes: 0