Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- namespace TestApp
- {
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Reflection;
- using System.Xml;
- using System.Xml.Linq;
- //using TheStore.Models;
- public static class XmlDataImporter
- {
- public static HashSet<T> ImportXmlData<T>(string filepath) where T : class // TODO validate params
- {
- var dataToImport = new HashSet<T>();
- var modelProperties = typeof(T).GetProperties();
- var nodeName = typeof(T).Name.ToLower();
- XDocument xmlDoc = XDocument.Load(filepath);
- var descendants = xmlDoc.Descendants(nodeName);
- foreach (var node in descendants)
- {
- var objToAdd = (T)Activator.CreateInstance(typeof(T));
- foreach (var prop in modelProperties)
- {
- var childNode = node.Element(prop.Name.ToLower());
- if (childNode != null)
- {
- var typeOfProperty = prop.PropertyType;
- var childValue = childNode.Value.Trim();
- var propValue = Convert.ChangeType(childValue, typeOfProperty);
- prop.SetValue(objToAdd, propValue, null);
- }
- }
- dataToImport.Add(objToAdd);
- }
- return dataToImport;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement