Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

How can i parse simple xml in .net

Posted on 2010-08-17
7
Medium Priority
?
328 Views
Last Modified: 2012-05-10
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


0
Comment
Question by:arildj78
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
7 Comments
 
LVL 18

Expert Comment

by:Anil Golamari
ID: 33455970
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
 
LVL 16

Accepted Solution

by:
kris_per earned 1040 total points
ID: 33456102

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
Fill in the form and get your FREE NFR key NOW!

Veeam® is happy to provide a FREE NFR server license to certified engineers, trainers, and bloggers.  It allows for the non‑production use of Veeam Agent for Microsoft Windows. This license is valid for five workstations and two servers.

 
LVL 60

Assisted Solution

by:HainKurt
HainKurt earned 960 total points
ID: 33456104
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
 
LVL 2

Author Comment

by:arildj78
ID: 33459698
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
 
LVL 2

Author Comment

by:arildj78
ID: 33459863
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
 
LVL 2

Author Closing Comment

by:arildj78
ID: 33459886
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

Featured Post

Ask an Anonymous Question!

Don't feel intimidated by what you don't know. Ask your question anonymously. It's easy! Learn more and upgrade.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
The article shows the basic steps of integrating an HTML theme template into an ASP.NET MVC project
In this video, Percona Solution Engineer Rick Golba discuss how (and why) you implement high availability in a database environment. To discuss how Percona Consulting can help with your design and architecture needs for your database and infrastr…
In a question here at Experts Exchange (https://www.experts-exchange.com/questions/29062564/Adobe-acrobat-reader-DC.html), a member asked how to create a signature in Adobe Acrobat Reader DC (the free Reader product, not the paid, full Acrobat produ…

636 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question