Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing GML data using C# Linq to XML

I know this is most likly very basic and been asked a thousand times but for some reason I just can't get it to work.

I have a gml file that looks like the following:

<?xml version='1.0' encoding='UTF-8'?>
<schema
xmlns='http://www.w3.org/2000/10/XMLSchema'
xmlns:gml='http://www.opengis.net/gml'
xmlns:xlink='http://www.w3.org/1999/xlink'
xmlns:xsi='http://www.w3.org/2000/10/XMLSchema-instance'
xsi:schemaLocation='http://www.opengis.net/gml/feature.xsd'>
<gml:Polygon srsName='http://www.opengis.net/gml/srs/epsg.xml#4283'>
 <gml:outerBoundaryIs>
  <gml:LinearRing>
   <gml:coord>
    <gml:X>152.035953</gml:X>
    <gml:Y>-28.2103190007845</gml:Y>
   </gml:coord>
   <gml:coord>
    <gml:X>152.035957</gml:X>
    <gml:Y>-28.2102020007845</gml:Y>
   </gml:coord>
   <gml:coord>
    <gml:X>152.034636</gml:X>
    <gml:Y>-28.2100120007845</gml:Y>
    </gml:coord>
   <gml:coord>
    <gml:X>152.034617</gml:X>
    <gml:Y>-28.2101390007845</gml:Y>
    </gml:coord>
   <gml:coord>
    <gml:X>152.035953</gml:X>
    <gml:Y>-28.2103190007845</gml:Y>
    </gml:coord>
  </gml:LinearRing>
 </gml:outerBoundaryIs>
</gml:Polygon>
</schema>

All I need to be able to do is read the X and Y from each gml:coord node. I am using C# 3.0 and LINQ so it should be easy but everything I try just returns empty results.

I have only done xml parsing in VB so the C# way is a bit foreign to me at the moment.

Thanks, Nathan

like image 406
Nathan W Avatar asked Nov 30 '09 06:11

Nathan W


1 Answers

My guess is that you haven't included the namespace. Here's a short but complete program which shows all the coords:

using System;
using System.Linq;
using System.Xml.Linq;

class Test
{
    static void Main()
    {
        XDocument doc = XDocument.Load("test.xml");
        XNamespace gml = "http://www.opengis.net/gml";

        var query = doc.Descendants(gml + "coord")
            .Select(e => new { X = (decimal) e.Element(gml + "X"),
                               Y = (decimal) e.Element(gml + "Y") });

        foreach (var c in query)
        {
            Console.WriteLine(c);
        }
    }
}
like image 70
Jon Skeet Avatar answered Oct 28 '22 23:10

Jon Skeet