我有一个xml文件,我要删除1个节点... 这就是它:
<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>
我的问题是......我想删除其中一个文件节点...其中包含“C:\ Users \ Stian \ Desktop \ toComp \ 334.jpg”作为内部文本......
目前我的代码(而且它不起作用):
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");
}
而我只是得到一个NullReferenceException ....当我尝试其他东西时...我现在没有代码..是否它删除了整个节点......
答案 0 :(得分:1)
如何使用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();
答案 1 :(得分:0)
XmlNode file = doc.SelectSingleNode("games/game[gameName='" + gName + "']/Files/file['" + liS + "']");
适合我