在 Windows Store App 中编辑 XML 文件 [英] Editing XML file in Windows Store App

查看:37
本文介绍了在 Windows Store App 中编辑 XML 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发 Windows 应用商店应用程序 (8.1),我对 XML 编写感到困惑.我的代码以正确的格式成功创建了 XML 文件.但是我不确定如何将新数据(新歌曲)添加到这个 xml 文件以及如何编辑现有的 xml 文件.长话短说,这是我目前的代码:

I am working on a Windows Store Application (8.1), and i got confused with XML writing. My code successfully creates XML file in a correct format. However i am not sure how to add new data(new songs) to this xml file and how to edit existing xml file. Long story short, here is my code so far:

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 文件是可以的,我只是创建根目录并向该根目录添加新元素,如下所示:

It is okay to work with non-existent xml file, i just create root and add new elements to this root like this:

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

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

The thing i need help with is, adding new data to xml file which already exists.

非常感谢您的反馈.

我的问候...

推荐答案

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

Instead of creating new element, you need to select the existing element, for example :

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

然后你可以像添加新的 <song> 元素一样:

Then you can do exactly the same way as you did to add new <song> element :

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

这篇关于在 Windows Store App 中编辑 XML 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆