Search code examples
c#xmlxmlreader

Read XML to a list<string[]> using xmlread


I am going to read an xml file of a gps points to a list and later convert them to a polygon and save in database. Here is my problem..When I try to read file every item in list is the same as others..can you help me with my problem?thanks in advanced here is my code:

  public List<string[]> loadXML(string xmlpath)
    {

        List<string[]> points = new List<string[]>();

        XmlReader xmlReader = XmlReader.Create(xmlpath);
        while (xmlReader.Read())
        {
            string[] item = new string[3];
            if ((xmlReader.NodeType == XmlNodeType.Element) && (xmlReader.Name == "trkpt"))
            {
                if (xmlReader.HasAttributes) 
                {

                    item[0] = xmlReader.GetAttribute("lat");
                    item[1] = xmlReader.GetAttribute("lon");

                }


            }
            if ((xmlReader.NodeType == XmlNodeType.Element) && (xmlReader.Name == "ele"))
            {


                    item[2] = xmlReader.ReadInnerXml();


            }
            points.Add(item);

        }
        return points;
    }

and here is a peice of my xml:

    <?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<gpx xmlns="" xmlns:gpxx="" xmlns:wptx1="" xmlns:gpxtpx="" creator="GPSMAP 78s" version="1.1" xmlns:xsi="" xsi:schemaLocation="">
<metadata>
<link href=""><text>Garmin International</text></link>
<time>2014-06-18T13:55:07Z</time></metadata>
<trk><name>PV164B2KHE</name>
<extensions><gpxx:TrackExtension><gpxx:DisplayColor>Cyan</gpxx:DisplayColor></gpxx:TrackExtension></extensions>
<trkseg>
<trkpt lat="31.0403929744" lon="51.5264290944"><ele>2089.08</ele><time>2014-06-18T13:45:57Z</time></trkpt>
<trkpt lat="31.0403881129" lon="51.5264252387"><ele>2088.60</ele><time>2014-06-18T13:46:01Z</time></trkpt></trkseg></trk></gpx>

I want to extract lat,lon and ele for each point


Solution

  • I would use Linq to XML for that:

    var xmlDocument = XDocument.Load("path");
    
    XNamepsace ns = xmlDocument.Root.GetDefaultNamespace();
    var values = xmlDocument.Root
                 .Descendants(ns + "trkpt")
                 .Select(x => new
                        {
                            lat = (string)x.Attribute("lat"), 
                            lon = (string)x.Attribute("lon"), 
                            ele = (string)x.Element(ns + "ele")
                        });
    

    Your mistake is xmlReader.Read() reads the next node, but you are creating a string[] array for each node.A node can not be a trkpt and ele at the same time. So that will never give you the desired result.