Pregunta

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

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

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

I would appreciate your feedback.

My Regards...

¿Fue útil?

Solución

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

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

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);
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top