How can i parse simple xml in .net

I have an xml string from some third party software. It contains metadata about some object and is delivered to me as string similar to sXml below.

//---------------------------------------
String sXml = "<Latitude>69.3</Latitude><Longitude>16.12</Longitude><Altitude>23</Altitude><Weather>Feels like winter</Weather>";

Now I want to extract this data and put it into my variables.

double Lat = -1 ;
double Lon = -1;
int Alt = -1;
String Weather = "" ;

DoTheFunkyThing(sXml, ref Lat, ref Lon, ref Alt, ref Weather); //Equivalent to magic

//---------------------------------------


Can someone help me figure out how to perform the magic? I'm able to hardcode a solution for this exact sXml, however I would like to learn how to use the classes in System.Xml namespace.

The way I see it, XML couldn't be any easier than my string; So why is it so hard to solve?

Arild


LVL 2
arildj78Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Anil GolamariCommented:
using System;
using System.Xml;

namespace ReadXMLfromFile
{
    /// <summary>
    /// description for Class1.
    /// </summary>
    class Class1
    {
        static void Main(string[] args)
        {
            XmlTextReader reader = new XmlTextReader ("sXml .xml");
            while (reader.Read())
            {
                switch (reader.NodeType)
                {
                    case XmlNodeType.Element: // The node is an element.
                        Console.Write("<" + reader.Name);
                        Console.WriteLine(">");
                        break;
                    case XmlNodeType.Text: //Display the text in each element.
                        Console.WriteLine (reader.Value);
                        break;
                    case XmlNodeType.EndElement: //Display the end of the element.
                        Console.Write("</" + reader.Name);
                        Console.WriteLine(">");
                        break;
                }
            }
            Console.ReadLine();
        }
    }
}
0
kris_perCommented:

Below is the DoTheFunkyThing method:
static void Main()
        {
            String sXml = "<Latitude>69.3</Latitude><Longitude>16.12</Longitude><Altitude>23</Altitude><Weather>Feels like winter</Weather>";
            double lat=0, lon=0, alt=0;
            string weather = "";

            DoTheFunkyThing(sXml, ref lat, ref lon, ref alt, ref weather);
}

public static void DoTheFunkyThing(string sXml, ref double Lat, ref double Lon, ref double Alt, ref string Weather)
        {
            sXml = string.Format("<mydata>{0}</mydata>", sXml);

            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.LoadXml(sXml);

            string val = GetNodeValue(xmlDoc.DocumentElement, "Latitude");
            Lat = Convert.ToDouble(val);

            val = GetNodeValue(xmlDoc.DocumentElement, "Longitude");
            Lon = Convert.ToDouble(val);

            val = GetNodeValue(xmlDoc.DocumentElement, "Altitude");
            Alt = Convert.ToDouble(val);

            Weather = GetNodeValue(xmlDoc.DocumentElement, "Weather");
        }

        private static string GetNodeValue(XmlNode parentNode, string nodeName)
        {
            XmlNode node = parentNode.SelectSingleNode(nodeName);
            return node.InnerText;
        }

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Cloud Class® Course: Microsoft Windows 7 Basic

This introductory course to Windows 7 environment will teach you about working with the Windows operating system. You will learn about basic functions including start menu; the desktop; managing files, folders, and libraries.

HainKurtSr. System AnalystCommented:
try this
        String sXml = "<data><Latitude>69.3</Latitude><Longitude>16.12</Longitude><Altitude>23</Altitude><Weather>Feels like winter</Weather></data>";

        XmlDocument doc = new XmlDocument();
        doc.LoadXml(sXml);

        double Lat = double.Parse(doc.SelectSingleNode("/data/Latitude").InnerText);
        double Lon = double.Parse(doc.SelectSingleNode("/data/Longitude").InnerText);
        int Alt = int.Parse(doc.SelectSingleNode("/data/Altitude").InnerText);

Open in new window

0
arildj78Author Commented:
Are there any chance of extracting the value by entering the tag as an argument?
Something similar to:

String sXml = "<Latitude>69.3</Latitude><Longitude>16.12</Longitude>" +
                      "<Altitude>23</Altitude><Weather>Feels like winter</Weather>";

String Weather = ExtractElementByTag( "Weather" );
0
arildj78Author Commented:
Sorry... forgot to refresh (for 6 hours....)

kris_per and HainKurt: Pretty much the same solution with the same timestamp. Did one of you cheat?
Anyway, your solutions was exactly what I was looking for. I have no idea why it was so hard to find that with google and msdn.

Below is the first part of my own implementation. Works perfectly :)
Lucky85: I'm sorry, but your solution was the same that I got from msdn and google; a sequential read through the document. Thanks for your time.


sXml = string.Format("<data>{0}</data>", PolyData0.ExtraData);

System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
xmlDoc.LoadXml(sXml);

string val = xmlDoc.SelectSingleNode("/data/Lat").InnerText;

Open in new window

0
arildj78Author Commented:
kris_per did supply the exact method I was asking for.
HainKurt did supply same solution, but with slightly shorter code (easy to read though).

CHEERS :)
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
.NET Programming

From novice to tech pro — start learning today.