updating an existing xml file in Windows Phone

后端 未结 1 1211
不思量自难忘°
不思量自难忘° 2020-12-12 07:31

I am using below piece of code to save the data to xml file in Windows Phone. First i am checking whether target xml file exists in the isolated storage or not; if it doesn

相关标签:
1条回答
  • 2020-12-12 07:39

    Set your open stream position to 0 or save XML document in the newly opened stream.

    XDocument doc = null;
    
    using (IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream(fileName, FileMode.Open, storage))
    {
        doc = XDocument.Load(isoStream);
        bool isUpdated = false;
        foreach (var item in (from item in doc.Descendants("Employee")
                         where item.Attribute("name").Value.Equals(empName)
                         select item).ToList())
        {
            // updating existing employee data
            // element already exists, need to update the existing attributes
            item.Attribute("name").SetValue(empName);
            item.Attribute("id").SetValue(id);
            item.Attribute("timestamp").SetValue(timestamp);
    
            isUpdated = true;
        }
    
        if (!isUpdated)
        {
            // adding new employee data
            doc.Element("Employee").Add(
                        new XAttribute("name", empName),
                        new XAttribute("id", id),
                        new XAttribute("timestamp", timestamp));
        }      
    
        //First way
        //isoStream.Position = 0;
        //doc.Save(isoStream);                  
    }
    
    //Or second way
    using (var stream = storage.OpenFile(fileName, FileMode.Open, FileAccess.Write))
    {
        doc.Save(stream);
    }       
    
    0 讨论(0)
提交回复
热议问题