Uso de la clase XElement para operar con XML

Existen varias clases para manipular XML, pero se descubrió que la clase XElement ofrece una forma muy conveniente de realizar estas operacciones. A continuación se muestran algunos métodos comunes.

  1. Crear XML
            XElement xml = new XElement("raiz", 
                new XElement("Padre", 
                    new XElement("Yo",
                        new XElement("hijo"),
                        new XElement("hija")
                )));

  1. Usando exprseiones lambda
            List<string> lista = new List<string>(){
                "Padre","Yo","hijo"
            };

            XElement xml=new XElement("raiz",
                lista.Select(x=>new XElement(x))
                );

            Console.WriteLine(xml);

            Dictionary<string, string> diccionario = new Dictionary<string, string>();
            diccionario.Add("Nombre", "zhangsan");
            diccionario.Add("Sexo", "masculino");
            diccionario.Add("Edad", "18");
            XElement xml=new XElement("raiz",
                diccionario.Select(x=>new XElement(x.Key,x.Value))
                );

            Console.WriteLine(xml);

  1. Crear a partir de una cadena, este método es el más sencillo
            string texto = "<Padre><Yo>Juan</Yo></Padre>";
            XElement xml = XElement.Parse(texto);

            Console.WriteLine(xml);

  1. Atributos
            XElement xml = new XElement("estudiantes", 
                new XElement("estudiante", 
                    new XAttribute("id", "1"), 
                    new XElement("nombre", "Juan"), 
                    new XElement("edad", 12)));

            string texto = "<estudiantes><estudiante id=\"1\"><nombre>Juan</nombre><edad>12</edad></estudiante></estudiantes>";
            XElement xml = XElement.Parse(texto);

            Console.WriteLine(xml);

  1. Guardar XML
            string texto = "<estudiantes><estudiante id=\"1\"><nombre>Juan</nombre><edad>12</edad></estudiante></estudiantes>";
            XElement xml = XElement.Parse(texto);

            xml.Save("archivo.xml");

  1. Cargar XML
            XElement xml = XElement.Load("archivo.xml");
            Console.WriteLine(xml);

  1. Leer XML
   
。。。。。{

 XElement xml = XElement.Load("archivo.xml");
           
            RecorrerXml(xml);
        }

        public static void RecorrerXml(XElement x)
        {
            MostrarXml(x);
            foreach (var elemento in x.Elements())
            {
                RecorrerXml(elemento);
            }
        }
        public static void MostrarXml(XElement x)
        {
            if (x == null)
                return;
            if (x.HasElements)
            {
                Console.WriteLine(x.Name);
            }
            else
            {
                Console.WriteLine(x.Name+":"+x.Value);
            }
            foreach (XAttribute atributo in x.Attributes())
            {
                Console.WriteLine("\t"+atributo.Name+":"+atributo.Value);
            }
        }

  1. Buscar un valor específico
            XElement xml = XElement.Load("archivo.xml");

            var elemento = xml.Descendants().Where(x =>
              {
                  var attr = (int?)x.Attribute("id");
                  if (attr != null)
                  {
                      if (attr.Value == 1)
                          return true;
                  }
                  return false;
                  //if (x.Value == "Juan")
                  //{
                  //    return true;
                  //}
                  //else
                  //{
                  //    return false;
                  //}
              });
            foreach (XElement x in elemento)
            {
                RecorrerXml(x);
            }

Etiquetas: XElement XML C# LINQ manipulación de datos

Publicado el 10-3 17:58