code_junkie

LINQ to XML optional element query

Nov 12th, 2011
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.30 KB | None | 0 0
  1. <Group>
  2. <Entry>
  3. <Name> Bob </Name>
  4. <ID> 1 </ID>
  5. </Entry>
  6. <Entry>
  7. <Name> Larry </Name>
  8. </Entry>
  9. </Group>
  10.  
  11. var items = from g in xDocument.Root.Descendants("Group").Elements("Entry")
  12. select new
  13. {
  14. name = (string)g.element("Name").Value,
  15. id = g.Elements("ID").Count() > 0 ? (string)g.Element("ID").Value : "none"
  16. };
  17.  
  18. var items =
  19. from g in xDocument.Root.Descendants("Group").Elements("Entry")
  20. select new
  21. {
  22. name = (string) g.Element("Name"),
  23. id = (string) g.Element("ID") ?? "none",
  24. };
  25.  
  26. var items =
  27. from g in xDocument.Root.Descendants("Group").Elements("Entry")
  28. select new
  29. {
  30. name = (string) g.Element("Name"),
  31. id = (int?) g.Element("ID"),
  32. };
  33.  
  34. public static string OptionalElement(this XElement actionElement, string elementName)
  35. {
  36. var element = actionElement.Element(elementName);
  37. return (element != null) ? element.Value : null;
  38. }
  39.  
  40. id = g.OptionalElement("ID") ?? "none"
  41.  
  42. var items = from g in xDocument.Root.Descendants("Group").Elements("Entry")
  43. let idEl = g.Element("ID")
  44. select new
  45. {
  46. name = (string)g.element("Name").Value,
  47. id = idEl == null ? "none" : idEl.Value;
  48. };
Add Comment
Please, Sign In to add comment