I am working on a class that creates or opens an xml file:
namespace QTabs
{
public class DataLayer
{
XmlDocument XMLDocObject = new XmlDocument();
StorageFolder storageFolder = ApplicationData.Current.LocalFolder;
StorageFile storageFile;
string xmlFile = "DataStore.xml";
public DataLayer()
{
loadXML();
}
public async void loadXML()
{
//if XML doc doesnt exist create it
try
{
storageFile = await ApplicationData.Current.LocalFolder.GetFileAsync(xmlFile);
}
catch (FileNotFoundException)
{
storageFile = null;
}
if (storageFile == null)
{
storageFile = await storageFolder.CreateFileAsync(xmlFile);
// Manipulate the xml document.
var root = XMLDocObject.CreateElement("SyncTimes");
XMLDocObject.AppendChild(root);
var childTag1 = XMLDocObject.CreateElement("id");
var childTag2 = XMLDocObject.CreateElement("dateTime");
root.AppendChild(childTag1);
root.AppendChild(childTag2);
await XMLDocObject.SaveToFileAsync(storageFile);
}
else
{
storageFile = await storageFolder.GetFileAsync(xmlFile);
}
}
public async void addSyncTime()
{
XmlElement x1 = XMLDocObject.CreateElement("SyncTime");
XmlElement x11 = XMLDocObject.CreateElement("id");
x11.InnerText = "1";
x1.AppendChild(x11);
XmlElement x12 = XMLDocObject.CreateElement("dateTime");
x12.InnerText = DateTime.Now.ToString();
x1.AppendChild(x12);
await XMLDocObject.SaveToFileAsync(storageFile);
}
}
}
My issue is with the above addSyncTime() method. When it runs it results in the XML file being empty, including removing the elements added on creation.
What am I doing wrong?
Hard to say without a good, minimal, complete code example that reliably reproduces the problem. However, your code appears to have two different problems:
XMLDocObject
referencing an empty document. (Indeed, the storageFile != null
case seems completely out of place; not only does it not load the XML from storageFile
as I'd expect, it actually re-retrieves the storageFile
object by calling GetFileAsync()
again).addSyncTime()
method creates new elements, but never adds them to the XML document tree.Given the above, I would expect the program behavior to be:
In neither case would I expect new SyncTime
elements to be added. The first time you run the program, you'll get the root SyncTimes
element and its initial id
and dateTime
children, but not any SyncTime
elements. After that, the XML document will be emptied, and you'll still not get any new SyncTime
elements.
If the above does not address your concern, please provide a good code example as described in the link I provide above.