Selecting Elements from an XML File Using LINQ

I have this XML structure:

<?xml version="1.0" encoding="UTF-8"?> <kml xmlns="http://www.opengis.net/kml/2.2"> <Document> <name>My Work</name> <Placemark> <name>Main Building</name> <Polygon> <extrude>1</extrude> <altitudeMode>relativeToGround</altitudeMode> <outerBoundaryIs> <LinearRing> <coordinates> </coordinates> </LinearRing> </outerBoundaryIs> </Polygon> </Placemark> <Placemark> <name>Office 1</name> <Polygon> <extrude>1</extrude> <altitudeMode>relativeToGround</altitudeMode> <outerBoundaryIs> <LinearRing> <coordinates> </coordinates> </LinearRing> </outerBoundaryIs> </Polygon> </Placemark> </Document> </kml> 

It continues...

I need to select the "name" of the building for each of them and save it inside the list. I wrote this code:

 using System; using System.Linq; using System.Xml; using System.Xml.Linq; using System.Collections.Generic; namespace dsdsdsds { public class Building { public string BuildingName { get; set; } } class MainClass { public static void Main(string[] args) { List<Building> buildingNames = (from e in XDocument.Load("buildings.kml").Root .Elements("Document") select new Building { BuildingName = (string)e.Element("name") }).ToList(); foreach (var e in buildingNames) { Console.WriteLine(e); } } } } 

However, it seems he doesnโ€™t want to output anything, and I canโ€™t find out where I am wrong. Can anyone help me?

thanks

+4
source share
3 answers

You forgot about the namespace declared in your xml:

 var xdoc = XDocument.Load("buildings.kml"); XNamespace kml = "http://www.opengis.net/kml/2.2"; var buildings = xdoc.Root.Elements(kml + "Document") .Select(d => new Building { BuildingName = (string)d.Element(kml + "name") }).ToList(); 
+6
source
 XDocument xDocument = XDocument.Load("buildings.kml"); XNamespace xNameSpace = "http://www.opengis.net/kml/2.2"; var names = from o in xDocument.Descendants(xNameSpace+"name") select o.Value; 

I think this is the easiest way; Remember to add a namespace before the requested item.

+2
source

From what I see, you are trying to iterate over the "Document" elements and select their names. Instead, you probably want to take another step in the Placemark element, i.e.

 XDocument.Load("buildings.kml").Element("Document").Elements("Placemark") select new Building { BuildingName = e.Element("name").Value }).ToList(); 
+1
source

All Articles