Skip to content

Instantly share code, notes, and snippets.

@Fhernd
Created November 29, 2015 18:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Fhernd/25f77f7038349e9865e7 to your computer and use it in GitHub Desktop.
Save Fhernd/25f77f7038349e9865e7 to your computer and use it in GitHub Desktop.
Uso de XmlDocument para crear un archivo XML en blanco e insertar elementos.
using System;
using System.Xml;
namespace Receptas.R0602
{
public class CreacionDocumentoXml
{
public static void Main()
{
// Creación de un nuevo documento XML en blanco:
XmlDocument docXml = new XmlDocument();
XmlNode nodoDoc = docXml.CreateXmlDeclaration("1.0", "UTF-8", null);
// Inserción del nodo reciénd creado al documento:
docXml.AppendChild(nodoDoc);
// Creación e inserción de nuevo nodo:
XmlNode nodoProductos = docXml.CreateElement("Productos");
docXml.AppendChild(nodoProductos);
// Creación de un nodo anidado:
XmlNode nodoProducto = docXml.CreateElement("Producto");
XmlAttribute atributoProducto = docXml.CreateAttribute("ID");
atributoProducto.Value = "10001";
nodoProducto.Attributes.Append(atributoProducto);
nodoProductos.AppendChild(nodoProducto);
// Creación de nuevos elementos para el nodo recién creado:
XmlNode nodoNombre = docXml.CreateElement("NombreProducto");
nodoNombre.AppendChild(docXml.CreateTextNode("Café Negro"));
nodoProducto.AppendChild(nodoNombre);
XmlNode nodoPrecio = docXml.CreateElement("Precio");
nodoPrecio.AppendChild(docXml.CreateTextNode("8500"));
nodoProducto.AppendChild(nodoPrecio);
// Creación de otro elemento para el nodo `nodoProductos`:
nodoProducto = docXml.CreateElement("Producto");
atributoProducto = docXml.CreateAttribute("ID");
atributoProducto.Value = "10002";
nodoProducto.Attributes.Append(atributoProducto);
nodoProductos.AppendChild(nodoProducto);
nodoNombre = docXml.CreateElement("NombreProducto");
nodoNombre.AppendChild(docXml.CreateTextNode("Cappuccino"));
nodoProducto.AppendChild(nodoNombre);
nodoPrecio = docXml.CreateElement("Precio");
nodoPrecio.AppendChild(docXml.CreateTextNode("9500"));
nodoProducto.AppendChild(nodoPrecio);
// Muestra el contenido del archivo en la salida estándar:
docXml.Save(Console.Out);
Console.ReadLine ();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment