How to read xml with c#

Asked

Viewed 4,504 times

2

I want to create an application for android with C# using Xamarin, it takes in a "database" xml some information and puts it on the screen, but I’m not able to manipulate xml.

I need to search the "symbol" in xml and if I find to take the information and put in variables, but I’m not getting:

Example of xml:

<?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 the StreamReader:

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

Gives the following error:

Error CS0246: The type or namespace name 'Streamreader' could not be found (are you Missing a using Directive or an Assembly Reference? ) (CS0246)

I thought I’d use the XmlTextReader but I don’t know how to do it, someone can help me?

  • add using System.IO; at the beginning of the file.

  • now the error is this: Error CS0246: The type or namespace name 'Xdocument' could not be found (are you Missing a using Directive or an Assembly Reference? ) (CS0246)

  • 2

    Can you put your full code in the question, please?

  • @Luke makes reference to System.Xml.Linq in your project and add using System.Xml.Linq in his .cs.

  • @Lucas who creates XML? The schema was set by you?

  • Take a look at that question, and I hope it helps you get what you need. http://answall.com/questions/13087/o-que%C3%A9-serializa%C3%A7%C3%A3o-when-to-use-how-to-implement-no-c

  • add using System.xml.Linq; at the beginning of the file.

  • Thank you all, but... anyone knows of any tutorial that can handle xml files with the Xdocument? c.c class

Show 3 more comments

2 answers

3

Here’s a basic demo using the W3C DOM and Xpath. You can include it in a method that gets the symbol (DOM is a bureaucratic API - if your problem is more complex it might 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, while running the above program you get:

simbolo: G
nAtomic: 56
valencia: 5
  • A detail. The XmlTextReader is unnecessary, just pass the file path to the method .Load(string) Xmldocument. However, if you want to use XmlTextReader don’t forget to call the .Dispose().

  • The .Close() does not call the .Dispose() @Omni?

  • no. But the .Dispose() calls the .Close().

  • Ah, eh the opposite :) I will correct. Thank you.

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();
  • Unless you use the let to verify that the element exists (i.e where simbolo != null, are not necessary and can put the x.Element(...).Value directly into select in order to make the code more intuitive.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.