Advertisement
svetlai

xml

Oct 18th, 2015
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.44 KB | None | 0 0
  1. namespace TestApp
  2. {
  3.     using System;
  4.     using System.Collections.Generic;
  5.     using System.Linq;
  6.     using System.Reflection;
  7.     using System.Xml;
  8.     using System.Xml.Linq;
  9.     //using TheStore.Models;
  10.  
  11.     public static class XmlDataImporter
  12.     {
  13.         public static HashSet<T> ImportXmlData<T>(string filepath) where T : class   // TODO validate params
  14.         {
  15.             var dataToImport = new HashSet<T>();
  16.             var modelProperties = typeof(T).GetProperties();
  17.             var nodeName = typeof(T).Name.ToLower();
  18.  
  19.             XDocument xmlDoc = XDocument.Load(filepath);
  20.             var descendants = xmlDoc.Descendants(nodeName);
  21.  
  22.             foreach (var node in descendants)
  23.             {
  24.                 var objToAdd = (T)Activator.CreateInstance(typeof(T));
  25.                 foreach (var prop in modelProperties)
  26.                 {
  27.                     var childNode = node.Element(prop.Name.ToLower());
  28.                     if (childNode != null)
  29.                     {
  30.                         var typeOfProperty = prop.PropertyType;
  31.                         var childValue = childNode.Value.Trim();
  32.                         var propValue = Convert.ChangeType(childValue, typeOfProperty);
  33.                         prop.SetValue(objToAdd, propValue, null);
  34.                     }
  35.                 }
  36.  
  37.                 dataToImport.Add(objToAdd);
  38.  
  39.             }
  40.  
  41.             return dataToImport;
  42.         }
  43.     }
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement