public static ProjectModel FromXElement(XElement element) { XElement root = "ProjectModel".Equals(element.Name.LocalName) ? element : element.Element("ProjectModel"); if (root == null) { return null; } ProjectModel model = new ProjectModel(); model.ProjectName = root.Element("ProjectName").Value; model.Version = root.Element("Version").Value; IEnumerable<XElement> groups = root.Elements("Groups"); foreach (var group in groups.Descendants("Group")) { model.Groups.Add(group.Value); } IEnumerable<XElement> screens = root.Elements("Screens"); foreach (var screen in screens.Descendants("Screen")) { model.Screens.Add(Screen.FromXElement(screen)); } return model; }
static void Main(string[] args) { List<Screen> screens = new List<Screen>(); screens.Add( new Screen() { ID = "this_is_test_id", Name = "Screen 1", Version = "1.0.0.1" }); screens.Add( new Screen() { ID = "2222 35", Name = "Screen 2", Version = "1.0.0.2" }); List<string> groups = new List<string>(); groups.Add("group1"); groups.Add("group2"); ProjectModel model = new ProjectModel() { ProjectName = "Test Project Name", Version = "2.0.1", Groups = groups, Screens = screens }; XElement element = model.ToXElement(); XDocument doc = new XDocument(new XDeclaration("1.0", "utf-8", "yes"), element); doc.Save(@"C:\Temp\obj2xml.xml"); doc = XDocument.Load(@"C:\Temp\obj2xml.xml"); ProjectModel mdf = ProjectModel.FromXmlProjectModel(doc); Console.WriteLine("Project Name: {0}", mdf.ProjectName); Console.WriteLine("Version: {0}", mdf.Version); foreach (var group in mdf.Groups) { Console.WriteLine("Group: {0}", group); } foreach (var screen in mdf.Screens) { Console.WriteLine("Screen Version: {0}", screen.Version); Console.WriteLine("Screen ID: {0}", screen.ID); Console.WriteLine("Screen Name: {0}", screen.Name); } }