编辑XML文件在Windows商店应用程序

本文关键字:应用程序 Windows XML 文件 编辑 | 更新日期: 2023-09-27 18:02:55

我正在开发一个Windows 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文件,我只是创建根并添加新元素到这个根,像这样:

    XmlText textname = xmlDoc.CreateTextNode("test12");
    childertag.AppendChild(textname);

我需要帮助的是,添加新的数据到已经存在的xml文件。

感谢您的反馈。

我问候…

编辑XML文件在Windows商店应用程序

您需要选择现有的元素,而不是创建新元素,例如:

var existingRoot = xmlDoc.SelectSingleNode("//music");

然后你可以做完全相同的方式来添加新的<song>元素:

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);