c# - Read XML file with LINQ and create object with IEnumerable propety -


here problem:

i have xml file:

<?xml version="1.0" encoding="utf-8" ?> <settings>   <app name="application1">     <log name="log1" path="d:\paths\" filename="log1file"/>     <log name="log2" path="d:\paths\"/>     <log name="log3" path="d:\paths\" filename="log3file"/>   </app> </settings> 

and i'm trying read linq , create object of class:

  public class apps   {     public string name { get; set; }     public ienumerable<logs> logs { get; set; }   }    public class logs   {     public string name { get; set; }     public string path { get; set; }     public string filename { get; set; }   } 

so far managed create bit of code looks gets first log element mean time need log elements each app element:

   public static ienumerable<apps> getallapps()     {       var items = in db.descendants("app")                   orderby a.attribute("name").value                   select new apps                   {                     name = a.attribute("name").value,                     logs = b in a.descendants("log")                            select new logs                             {                              name = b.attribute("name").value,                             path = b.attribute("path").value,                             filename = b.attribute("filename").value                            }                   };        return items;     } 

i used fluent api, let adapt prefer...

problem nullreferenceexception, 1 of logs in xml has no "filename" attribute. , when use "value" on null, nre.

so, check if attribute exists before trying it's value.

var = db.descendants("app")                     .orderby(app => app.attribute("name").value)                     .select(app => new apps() {                         name = app.attribute("name").value,                         logs = app.descendants("log").select(a =>                             new logs() {                                 name = a.attribute("name") != null ? a.attribute("name").value : null,                                 path = a.attribute("path") != null ? a.attribute("path").value : null,                                 filename = a.attribute("filename") != null ? a.attribute("filename").value : null                             }).tolist()                     }).tolist(); 

Comments

Popular posts from this blog

java - Play! framework 2.0: How to display multiple image? -

gmail - Is there any documentation for read-only access to the Google Contacts API? -

php - Controller/JToolBar not working in Joomla 2.5 -