Created
April 22, 2016 02:35
-
-
Save Fhernd/7fa5d80e0447d52df71f73bfb3553db0 to your computer and use it in GitHub Desktop.
Lectura y escritura de nodos usando las clases XmlWriter y XmlReader.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Xml; | |
using System.IO; | |
using System.Text; | |
namespace Recetas.CSharp.R0607 | |
{ | |
public class LecturaEscrituraXml | |
{ | |
public static void Main() | |
{ | |
// Crea archivo XML: | |
FileStream fsXml = new FileStream("productos.xml", FileMode.Create); | |
XmlWriter xmlWriter = XmlWriter.Create(fsXml); | |
// Indica el inicio de la escritura del documento: | |
xmlWriter.WriteStartDocument(); | |
// Especifica el nombre del primer elemento: | |
xmlWriter.WriteStartElement("Productos"); | |
// Escritura de un producto: | |
xmlWriter.WriteStartElement("Producto"); | |
xmlWriter.WriteAttributeString("ID", "1000001"); | |
xmlWriter.WriteElementString("NombreProducto", "Salmón Roll"); | |
xmlWriter.WriteElementString("Precio", "45.0"); | |
xmlWriter.WriteEndElement(); | |
// Escritura de un producto: | |
xmlWriter.WriteStartElement("Producto"); | |
xmlWriter.WriteAttributeString("ID", "1000002"); | |
xmlWriter.WriteElementString("NombreProducto", "Sushigo"); | |
xmlWriter.WriteElementString("Precio", "33.0"); | |
xmlWriter.WriteEndElement(); | |
// Cierre del documento: | |
xmlWriter.WriteEndElement(); | |
xmlWriter.WriteEndDocument(); | |
xmlWriter.Flush(); | |
fsXml.Close(); | |
Console.WriteLine ("\nLa escritura del documento XML ha finalizado."); | |
Console.WriteLine ("Presiona Enter para continuar con su lectura."); | |
Console.ReadLine (); | |
// Apertura del archivo: | |
fsXml = new FileStream("productos.xml", FileMode.Open); | |
XmlReader xmlReader = XmlReader.Create(fsXml); | |
// Lectura de todos los nodos del documento XML: | |
while(xmlReader.Read()) | |
{ | |
// Comprueba que el nodo actual sea de tipo Element: | |
if (xmlReader.NodeType == XmlNodeType.Element) | |
{ | |
Console.WriteLine (); | |
Console.WriteLine (String.Format("<{0}>", xmlReader.Name)); | |
// Comprueba que el elemento actual contenga atributos: | |
if (xmlReader.HasAttributes) | |
{ | |
for (int indiceAtributo = 0; indiceAtributo < xmlReader.AttributeCount; ++indiceAtributo) | |
{ | |
Console.WriteLine (String.Format("\tATRIBUTO: {0}", xmlReader.GetAttribute(indiceAtributo))); | |
} | |
} | |
} else if (xmlReader.NodeType == XmlNodeType.Text) | |
{ | |
Console.WriteLine (String.Format("\tVALOR: {0}", xmlReader.Value)); | |
} | |
} | |
Console.ReadLine (); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment