Retrocoder
Retrocoder

Reputation: 4703

Creating objects from XML

I have the following XML that uses the name “Part” in multiple locations. I just want to access the first level elements called “Part” and not for my Linq expression to also pickup the child elements called “Part”. I’ve used the following Linq to accomplish what I want but it seems a bit messy. Can it be improved ?

<Stuff>
  <Parts>
   <Part>
     <A>
       <Part>
         <B>10</B>
       </Part>
    </A>
 </Part>
   <Part>
     <A>
       <Part>
         <B>10</B>
       </Part>
     </A>
  </Part>
 </Parts>
</Stuff>


var pbp = data.Descendants("Part")
            .Where(b => b.Parent == data.Element("Parts"))
            .Select(b => (Part)Deserialise(b.ToString(), typeof(Part)));

return pbp.ToList();

Upvotes: 0

Views: 181

Answers (1)

Thomas Levesque
Thomas Levesque

Reputation: 292355

Would you prefer that form ?

var pbp = from p in data.Element("Parts").Elements("Part")
          select (Part)Deserialise(p.ToString(), typeof(Part));
return pbp.ToList();

Upvotes: 1

Related Questions