Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

simple xml parsing

Tags:

c#

.net

parsing

xml

what is the simplest way to parse the lat and long out of the following xml fragment. There is no namespace etc.

It is in a string variable. not a stream.

<poi>
      <city>stockholm</city>
      <country>sweden</country>
      <gpoint>
        <lat>51.1</lat>
        <lng>67.98</lng>
      </gpoint>
</poi>

everything I have read so far is waaaaay too complex for what should be a simple task e.g. http://geekswithblogs.net/kobush/archive/2006/04/20/75717.aspx

I've been looking at the above link

Surely there is a simpler way to do this in .net?

like image 234
ChrisCa Avatar asked Feb 16 '09 03:02

ChrisCa


2 Answers

Use XElement.Parse(string text) method to do this.

Example:

string xmlString = @"<poi>
              <city>stockholm</city>
              <country>sweden</country>
              <gpoint>
                <lat>51.1</lat>
                <lng>67.98</lng>
              </gpoint>
          </poi>";
        try
        {
            XElement x = XElement.Parse(xmlString);
            var latLng = x.Element("gpoint");

            Console.WriteLine(latLng.Element("lat").Value);
            Console.WriteLine(latLng.Element("lng").Value);
        }
        catch
        {
        }

Hope this helps!

like image 113
Mohamed Alikhan Avatar answered Oct 21 '22 02:10

Mohamed Alikhan


Using Linq for XML:

   XDocument doc= XDocument.Parse("<poi><city>stockholm</city><country>sweden</country><gpoint><lat>51.1</lat><lng>67.98</lng></gpoint></poi>");

    var points=doc.Descendants("gpoint");

    foreach (XElement current in points)
    {
        Console.WriteLine(current.Element("lat").Value);
        Console.WriteLine(current.Element("lng").Value);
    }

    Console.ReadKey(); 
like image 38
Ash Avatar answered Oct 21 '22 02:10

Ash