lunes, 28 de diciembre de 2015

Generar XML con StringWriter con C#

Os muestro una forma sencilla de generar un XML, a partir de la clase StringWriter en C#.
Lo primero es crear el objeto:

StringWriter sw = new StringWriter(new StringBuilder(String.Empty));
XmlTextWriter xmlWriter = new XmlTextWriter(sw);
xmlWriter.Formatting = Formatting.Indented;
xmlWriter.Indentation = 5;  // Tabulaciones en el XML


 A continuación indicarle la codificación:


xmlWriter.WriteProcessingInstruction("xml", "version=\"1.0\" encoding=\"UTF-8\"");
 

Posteriormente creamos las etiquetas que necesitemos, en este caso creamos una etiqueta "BLOG", antes de cerrarla con xmlWriter.WriteEndElement(); podemos crear más etiquetas dentro de la etiqueta BLOG, en este caso creamos etiquetas ENTRADA, que como se puede ver se le puede agregar atributos gracias a la función: WriteAttributeString.

xmlWriter.WriteStartElement("BLOG");
    xmlWriter.WriteStartElement("ENTRADA");
        xmlWriter.WriteAttributeString("CODIGO", "1");
        xmlWriter.WriteAttributeString("DESCRIPCION", "Generar XML 1");
    xmlWriter.WriteEndElement();
   
    xmlWriter.WriteStartElement("ENTRADA");
        xmlWriter.WriteAttributeString("CODIGO", "2");
        xmlWriter.WriteAttributeString("DESCRIPCION", "Generar XML 2");
    xmlWriter.WriteEndElement();
   
xmlWriter.WriteEndElement(); // Cierre etiqueta BLOG

String cadenaXML = sw.ToString();


La cadena de texto con el XML quedaría de la siguiente forma:

<?xml version="1.0" encoding="UTF-8"?>
<BLOG>
     <ENTRADA CODIGO="1" DESCRIPCION="Generar XML 1" />
     <ENTRADA CODIGO="2" DESCRIPCION="Generar XML 2" />
</BLOG>

No hay comentarios:

Publicar un comentario