Guardar Información en un XML
Lo primero fue crear el formulario web (CSTestAdd.aspx), a este le agregué unos controles AJAX (no es obligatorio)
Esto es: Dos TextBox (txtName, txtDate), un control Edit de AJAX (txtDescription), un Button (btnAddSample) y un Label (lblResult).
<?xml version=»1.0″ encoding=»utf-8″?>
<Samples>
<Sample SampleID=»»>
<SampleName></SampleName>
<SampleDate></SampleDate>
<SampleDescription></SampleDescription>
</Sample>
</Samples>
El codigo correspondiente (CSTestAdd.aspx.cs) es el siguiente:
1. Aregar referencias
using System.Xml;
using System.IO;
2. Se crea un método en el cual se ingresan los valores del formulario:
Analizando un poco el código, creamos un string (myPath) con la ruta en donde se encuentra guardado nuestro archivo xml utilizando el método MapPath().
Se crea una instancia de XmlDocument (docA), si el archivo existe le asigno la ruta a esta instancia docA.Load(myPath).
A partir de este punto se llaman los elementos (XmlElement) y atributos (XmlAttribute) que deben incluirse dentro de nuestro archivo xml, asignandole el registro de datos a través de las variables del metodo que creamos
void AddData(string SampleID, string SampleDate, string SampleName, string SampleDescription)
{
try
{
string myPath = MapPath(«~/App_Data/Samples.xml»);
XmlDocument docA = new XmlDocument();
if(File.Exists(myPath))
{
docA.Load(myPath);
XmlElement SampleRoot = docA.DocumentElement;
XmlElement Sample = docA.CreateElement(«Sample»);
XmlAttribute SAt = docA.CreateAttribute(«SampleID»);
SAt.Value = SampleID;
Sample.Attributes.Append(SAt);
SampleRoot.AppendChild(Sample);
XmlElement SDate = docA.CreateElement(«SampleDate»);
XmlText textDate = docA.CreateTextNode(SampleDate);
SampleRoot.LastChild.AppendChild(SDate);
SampleRoot.LastChild.LastChild.AppendChild(textDate);
XmlElement SName = docA.CreateElement(«SampleName»);
XmlText textName = docA.CreateTextNode(SampleName);
SampleRoot.LastChild.AppendChild(SName);
SampleRoot.LastChild.LastChild.AppendChild(textName);
XmlElement SDesc = docA.CreateElement(«SampleDescription»);
XmlText textDesc = docA.CreateTextNode(SampleDescription);
SampleRoot.LastChild.AppendChild(SDesc);
SampleRoot.LastChild.LastChild.AppendChild(textDesc);
SampleRoot.InsertAfter(Sample, SampleRoot.LastChild);
docA.Save(myPath);
lblResult.Text = «New <b>» + txtName.Text + «</b> Stored»;
}
}
catch(Exception ex)
{
lblResult.Text = ex.Message + «<br/>» + ex.StackTrace;
}
}
3. Crear un método para la creación de un id. Este metodo busca el valor del último id y retorna ese valor para incrementarlo cuando el evento del botón. El objetivo es crear un esquema pseudo-autoincremental:
int TakeId()
{
int last;
string id;
string myPath = MapPath(«~/App_Data/Samples.xml»);
XmlDocument docA = new XmlDocument();
docA.Load(myPath);
try
{
XmlNodeList SID = docA.GetElementsByTagName(«Sample»);
last = SID.Count;
XmlNode nodo = SID.Item(last – 1);
id = nodo.Attributes[0].Value;
return Convert.ToInt32(id);
}
catch
{
return 0;
}
}
4. Creamos el evento del botón en donde llamamos los métodos TakeId() y AddData():
protected void btnAddSoluiton_Click(object sender, EventArgs e)
{
int id;
id = TakeId() + 1;
AddData(id.ToString(), txtDate.Text, txtName.Text, txtDescription.Content);
}
Los invito a probarlo y mejorarlo para que puedan utilizarlo en sus aplicaciones.
Justo lo que necesitaba, nadamas que en vb.. pero ya quedó.. excelente
Me gustaMe gusta