【问题标题】:Editing XML file in Windows Store App在 Windows Store App 中编辑 XML 文件
【发布时间】:2014-05-13 08:56:37
【问题描述】:

我正在开发一个 Windows 应用商店应用程序 (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 文档中选择要修改的元素(添加新的子元素,或更改元素值)。请澄清,您想将新的<song> 元素添加到现有的<music>
  • 是的,正确的。像这样: Song1Singer1testSong2Singer2test2 如何从现有的 XML 文档中选择元素?感谢回复!
  • 检查我的答案,我假设您在现有 XML 中只有一个 <music> 元素..

标签: c# xml windows-store-apps


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多