Pregunta

Estoy usando la parte inferior de un código para guardar los datos en el archivo XML en Windows Phone.Primero estoy comprobando si existe el archivo XML de destino en el almacenamiento aislado o no; Si no existe, estoy creando el archivo y agregue los datos de elementos requeridos.Si existe el archivo, la primera comprobación de si el elemento ya existe, si es así, estoy actualizando los valores del atributo, de lo contrario, agregando un elemento nuevo al archivo XML.

El problema que estoy viendo es, si ya existe el elemento e intentando actualizar los atributos (W / ABATIVO DE ABAJO): estoy viendo un elemento adicional agregado con nuevos datos y aún existe datos antiguos en el archivo.No se está actualizando en su lugar anexar.

using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (storage.FileExists(fileName))
                {
                    using (IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream(fileName, FileMode.Open, storage))
                    {
                        XDocument 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));
                        }

                        doc.Save(isoStream);
                    }
                }
                else
                {
                    // creating XML file and adding employee data
                    using (IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream(fileName, FileMode.Create, storage))
                    {
                        XDocument doc = new XDocument(new XDeclaration("1.0", "utf8", "yes"),
                            new XElement("Employees",
                                new XElement("Employee",
                                    new XAttribute("name", empName),
                                    new XAttribute("id", id),
                                    new XAttribute("timestamp", timestamp))));

                        doc.Save(isoStream, SaveOptions.None);
                    }
                }
            }

¿Fue útil?

Solución

Configure su posición de flujo abierto en 0 o ahorre el documento XML en el flujo recién abierto.

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

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top