C# XML User Management: Alta and Baja Methods

Spanish2.46 KB

User Maintenance in C# with XML

Querying a User by Key

The following LINQ to XML query retrieves a user element from the Usuarios collection by matching the Clave attribute:

var usuarioxml = (from usu in datos.DocumentoXML.Elements("Usuarios").Elements("Usuario")
where usu.Attribute("Clave").Value.Equals(clave)
select usu).SingleOrDefault();

The MantenimientoXML Class

The MantenimientoXML class implements the IMantenimiento interface and manages users stored in an XML file.

public class MantenimientoXML : IMantenimiento
{
    private ProcesosXML _procesos;

    public MantenimientoXML(string filename)
    {
        _procesos = new ProcesosXML(filename);
    }

    public IProcesos Proceso
    {
        get { return Proceso; }
        set { _procesos = value as ProcesosXML; }
    }

    public bool Alta(IElemento elemento)
    {
        DataSourceXML datos = _procesos.Datos as DataSourceXML;
        //compruebo si existe el usuario
        if (usuarioxml != null)
            return false;

        Usuario nuevo = elemento as Usuario;
        XElement nuevoUsu = new XElement("Usuario",
                        new XAttribute("Clave", nuevo.Clave),
                        new XElement("Nombre", nuevo.Nombre),
                        new XElement("Edad", nuevo.Edad));

        var usuarios = (from usu in datos.DocumentoXML.Elements("Usuarios")
                        select usu).SingleOrDefault();
        usuarios.Add(nuevoUsu);
        datos.GuardarDatos();
        return true;
    }

    public bool Baja(string clave)
    {
        DataSourceXML datos = _procesos.Datos as DataSourceXML;
        //compruebo si existe el usuario
        if (usuarioxml == null)
            return false;

        usuarioxml.Remove();
        datos.GuardarDatos();
        return true;
    }
}

Key Points

  • The Alta method adds a new user only if the key does not already exist.
  • The Baja method removes an existing user and saves the changes.
  • Both methods call GuardarDatos() to persist the XML document.

Download

PDF Word HTML