C # deserializar XML to read and collect data

1

I have an application in Unity and I have a class where I assign some buttons a text. I want the button texts to be imported from an XML file. I have done this to read the XML but I do not know how to get the data and take it to the other class.

This is my code:

Public void leerXml()
{
   datos libros = null;
   string path= @"C:\libros.xml"
   XmlSerializer serializer = nwe xmlSerializer(typeof(datos));
   StreamReader reader = new StreamReader(path);
   libros = (datos)serializer.deserialize(reader):
   reader.close
}

This is my XML

<libro> 
  <libroEjemplo>
       <libro1>
          <nombre>Alfredo Reino</nombre> 
          <email>alf@ibium.com</email> 
       </libro1>
  </libroEjemplo>

  <libroEjemplo>
       <libro2>
          <nombre>Alfredo Reino</nombre> 
          <email>alf@ibium.com</email> 
       </libro2>
  </libroEjemplo>
<libro>

I think that I have it right and I read the XML data, but how can I get them and take them to another class to assign the XML texts to the buttons?

    
asked by JuanPerez 29.03.2017 в 17:29
source

3 answers

1

The best thing is that you have a property in the class where you deserialize the xml that returns the value of the read. It would be something like this:

public class LectorXML
{ 
    private datos libros;
    public datos Libros
    {
         get{
            return this.libros;
         }
    }

    public void leerXml()
    {
       string path= @"C:\libros.xml"
       XmlSerializer serializer = nwe xmlSerializer(typeof(datos));
       StreamReader reader = new StreamReader(path);
       libros = (datos)serializer.deserialize(reader):
       reader.close
    }
}

Once this is done, in the other class you would do something like this:

LectorXML lector= new LectorXML();
lector.leerXml();
LectorXML.datos libros=lector.Libros;

Another option is for your leerXml method to return the read data:

public datos leerXml()
{
   string path= @"C:\libros.xml"
   XmlSerializer serializer = nwe xmlSerializer(typeof(datos));
   StreamReader reader = new StreamReader(path);
   libros = (datos)serializer.deserialize(reader):
   reader.close
   return libros;
}

With what from your other class, the code would be something like:

LectorXML lector= new LectorXML();
LectorXML.datos libros=lector.leerXml();
    
answered by 29.03.2017 в 17:49
1

You can use DataSets , In my opinion they are easier to use than XMLSerializer , although it has its pros and cons.

DataSet ds = new DataSet("miDataSet");
        ds.ReadXml("RutaDeMiXML");

        foreach (DataTable tabla in ds.Tables)
        {
            Console.WriteLine("La tabla " + tabla.TableName + " Tiene los siguientes campos");
            foreach (DataRow row in tabla.Rows)
            {
                Console.Write("nombre: " + row["nombre"].ToString());
                Console.Write("email: " + row["email"].ToString());
            }
        }
    
answered by 29.03.2017 в 17:53
1

First I suggest you make a modification to the structure of your XML: Unless your application requires it, you should be able to add <libro1> and <libro2> as <libro> each, both within the <librosEjemplo> element.

<libroRaiz>
    <librosEjemplo>
        <libro>
            <nombre></nombre>
            <email></email>
        </libro>
        <libro>
            <nombre></nombre>
            <email></email>
        </libro>
    </librosEjemplo>
<libroRaiz>

Based on this suggestion:

I would use System.Xml.Linq; in the following way

// se Carga todo el XML en el objeto libro
XDocument libroRaiz = XDocument.Load("tuarchivo.xml", LoadOptions.None);
//usa éste siguiente para cargar desde texto (string) en vez de un archivo
//XDocument doc = XDocument.Parse(texto);

//Obtener objeto librosEjemplo
XElement librosEjemplo = libroRaiz.Element("librosEjemplo");

//Obtener lista de libros dentro de librosEjemplo
IEnumerable<XElement> libros = librosEjemplo.Descendants("libro");

//has un foreach y por cada uno haz lo que tengas que hacer
foreach(XElement libro in libros)
{
    string nombre = libro.Element("nombre").Value;
    string email = libro.Element("email").Value;
    ...
}

I put it step by step so you could appreciate what each part does, but you can do it in one line:

IEnumerable<XElement> libros = XDocument.Load("tuarchivo.xml", LoadOptions.None).Element("librosEjemplo").Descendants("libro");

foreach(XElement libro in libros) { ... }
    
answered by 29.03.2017 в 18:30