Harmen
Harmen

Reputation: 992

Linq simple XML snippet to non-anonymous type

I am trying to parse this piece of XML

<?xml version='1.0' encoding='UTF-8' standalone='yes' ?>
 <DagUren>
   <Chauffeur>Vincent</Chauffeur>
   <AanmeldTijd>4 dec. 2012 09:05:42</AanmeldTijd>
   <Gewerkt>04:42</Gewerkt>
 </DagUren>

I created a DagUren class that contains strings with Chauffer, AanmeldTijd, Gewerkt, etc.

        DagUren eenDagUren
            = (from du in doc.Element("DagUren")
               select new DagUren
               {
                   Chauffeur = du.Element("Chauffeur").Value,
                   Gewerkt = du.Element("Gewerkt").Value,
                   Pauze = du.Element("Pauze").Value,
                   AanmeldTijd = du.Element("AanmeldTijd").Value,
               }
         );

The compiler respons with: Could not find an implementation of the query pattern for source type 'System.Xml.Linq.XElement'. 'Select' not found.

Please advice, i've spend quite some time on it rewriting, every guide is using a different approach...

Upvotes: 2

Views: 234

Answers (2)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236208

Thats because Select is an extension for IEnumerable, but you are selecting single element. Make query on enumerable, and apply SingleOrDefault at the end:

 DagUren eenDagUren
            = (from du in doc.Elements("DagUren")
               select new DagUren
               {
                   Chauffeur = du.Element("Chauffeur").Value,
                   Gewerkt = du.Element("Gewerkt").Value,
                   Pauze = du.Element("Pauze").Value,
                   AanmeldTijd = du.Element("AanmeldTijd").Value,
               }).SinleOrDefault();

Or simply (thus you have only one node to parse, which is root). Consider also to use nodes casting, instead of reading Value properties:

 XElement root = doc.Root;
 DagUren eenDagUren = new DagUren() {
               Chauffeur = (string)root.Element("Chauffeur"),
               Gewerkt = (TimeSpan)root.Element("Gewerkt"),
               Pauze = (bool)root.Element("Pauze"), // e.g. 
               AanmeldTijd = (DateTime)root.Element("AanmeldTijd") });

Upvotes: 0

Jan P.
Jan P.

Reputation: 3297

Your problem is, that Element() does not return a collection of XElement it just returns a single object. Linq just queries collections of items, not single objects. So your solution would be:

XElement du = doc.Element("DagUren");
DagUren ennDagUren =
    new DagUren
        { 
            Chauffeur = du.Element("Chauffeur").Value,
            Gewerkt = du.Element("Gewerkt").Value,
            Pauze = du.Element("Pauze").Value,
            AanmeldTijd = du.Element("AanmeldTijd").Value
        };

Upvotes: 2

Related Questions