How to read xml with C #

2

I want to create an application for android with C # using Xamarin, it takes an information "xml" and puts it on the screen, but I can not manipulate xml.

I need to look for the "symbol" in the xml and if I find the information and put it in variables, however I can not:

xml example:

<?xml version="1.0" encoding="utf-8" ?>
<Itens>
  <tb>
    <simbolo>G</simbolo>
    <nAtomic>56</nAtomic>
    <valencia>5</valencia>
  </tb>
  <tb>
    <simbolo>Ga</simbolo>
    <nAtomic>565</nAtomic>
    <valencia>55</valencia>
  </tb>          
</Itens>

When I use StreamReader :

StreamReader strm = new StreamReader ("Db.xml"); 
XDocument xd = XDocument.Load(strm); //......

It gives the following error:

  

Error CS0246: The type or namespace name 'StreamReader' could not be found (CS0246)

I thought about using XmlTextReader but I do not know how I can, can anyone help me?

    
asked by anonymous 05.08.2014 / 01:18

2 answers

3

Here's a basic demo using W3C DOM and XPath. You can include in a method that receives the symbol (DOM is a bureaucratic API - if your problem is more complex it may be simpler if you use Linq.)

using System;
using System.Xml;
using System.Xml.XPath;

namespace XmlTest
{
    public class TesteXML
    {
        public static void Main (string[] args)
        {
            XmlTextReader reader = new XmlTextReader("Db.xml");
            XmlDocument doc = new XmlDocument(); 
            doc.Load(reader);
            reader.Dispose();

            string simbolo = "G";
            XmlElement tb = doc.SelectSingleNode("//tb[simbolo='"+simbolo+"']") as XmlElement;

            Console.WriteLine("simbolo: "  + tb.GetElementsByTagName("simbolo")[0].InnerText);
            Console.WriteLine ("nAtomic: " + tb.GetElementsByTagName ("nAtomic")[0].InnerText);
            Console.WriteLine("valencia: " + tb.GetElementsByTagName("valencia")[0].InnerText);
        }
    }
}

Using the file you provided, by running the above program you get:

simbolo: G
nAtomic: 56
valencia: 5
    
07.08.2014 / 16:18
2

Another way is XDocument and Linq.

var resultado = (from x in System.Xml.Linq.XDocument.Parse(System.IO.File.ReadAllText(".\Db.Xml"))
                   .Descendants("tb")
                   let simbolo = x.Element("simbolo").Value
                   let nAtomic = x.Element("nAtomic").Value
                   let valencia = x.Element("valencia").Value
                   select new 
                   {
                           simbolo, 
                           nAtomic, 
                           valencia
                   })
                   .ToArray();
    
12.08.2014 / 04:08