在Windowsapp store应用中编辑XML文件
我正在开发一个Windowsapp store应用程序(8.1),我对XML编写感到困惑。 我的代码以正确的格式成功创建XML文件。 但是,我不知道如何向此xml文件添加新数据(新歌曲)以及如何编辑现有的xml文件。 长话短说,这是我的代码到目前为止:
StorageFolder sf = await ApplicationData.Current.LocalFolder.CreateFolderAsync("UserInputData", CreationCollisionOption.OpenIfExists); StorageFile st = await sf.CreateFileAsync("MusicData.xml", CreationCollisionOption.OpenIfExists); XmlDocument xmlDoc = new XmlDocument(); var content = await FileIO.ReadTextAsync(st); if (!string.IsNullOrEmpty(content)) { xmlDoc.LoadXml(content); } else { var root = xmlDoc.CreateElement("music"); xmlDoc.AppendChild(root); var childTag = xmlDoc.CreateElement("song"); root.AppendChild(childTag); var childertag = xmlDoc.CreateElement("name"); childTag.AppendChild(childertag); var childertag2 = xmlDoc.CreateElement("singer"); childTag.AppendChild(childertag2); var childertag3 = xmlDoc.CreateElement("chords"); childTag.AppendChild(childertag3); } await xmlDoc.SaveToFileAsync(st);
可以使用不存在的xml文件,我只需创建root并向此根添加新元素,如下所示:
XmlText textname = xmlDoc.CreateTextNode("test12"); childertag.AppendChild(textname);
我需要帮助的是,将新数据添加到已存在的xml文件中。
非常感谢您的反馈。
致以我的问候…
您需要选择现有元素,而不是创建新元素,例如:
var existingRoot = xmlDoc.SelectSingleNode("//music");
然后,您可以像添加新的
元素一样完成相同的操作:
var childTag = xmlDoc.CreateElement("song"); existingRoot.AppendChild(childTag); var childertag = xmlDoc.CreateElement("name"); childTag.AppendChild(childertag); var childertag2 = xmlDoc.CreateElement("singer"); childTag.AppendChild(childertag2); var childertag3 = xmlDoc.CreateElement("chords"); childTag.AppendChild(childertag3);