Monday, 21 July 2014

Read the XML Embedded Resource file in C#


Just add one XML file to your solution .






in above solution i  have added master.xml file and i set the properties BuildAction : Embedded Resource   and Copy to OutPut : Copy if Newer .

add these two name Spaces     using System.Xml.Linq;  
                                             using System.Xml;


define one class :-

class schemas
    {
     
     
        public int schemaId { get; set; }
     
        public string schemaName { get; set; }
    }

 class Category
    {
         
       
        public int categoryId { get; set; }
     
        public string categoryName { get; set; }
       
    }

class userInfo
    {
       
        public int userId { get; set; }
       
        public string firstName { get; set; }
       
        public string lastName { get; set; }
    }

 using System.Xml.Linq;  
 using System.Xml;
namespace PatrolInfromationSystem
{
 public class DBHelper
    {

         List<Model.Category> catlst = null;
        List<Model.userInfo> usrlst = null;
        List<Model.schemas> schemelst = null;

DBHelper()
{
 XDocument doc;

                var asm = Assembly.GetExecutingAssembly();

                using (var stream =Assembly.GetExecutingAssembly().GetManifestResourceStream("PatrolInfromationSystem.master.xml"))
                  // Mandatory to specified with Namespace .
                {
                    doc = LoadFromStream(stream);
                }

                catlst = null;
                usrlst = null;
                schemelst = null;
                catlst = doc.Descendants("category").Select(d => new Model.Category { categoryId = Convert.ToInt16(d.Element("categoryId").Value), categoryName = d.Element("categoryName").Value }).ToList();
                usrlst = doc.Descendants("userInfo").Select(d => new Model.userInfo { userId = Convert.ToInt16(d.Element("userId").Value), firstName = d.Element("firstName").Value, lastName = d.Element("lastName").Value }).ToList();
                schemelst = doc.Descendants("schemas").Select(d => new Model.schemas { schemaId = Convert.ToInt16(d.Element("schemaId").Value), schemaName = d.Element("schemaName").Value }).ToList();
}

 static XDocument LoadFromStream(Stream stream)
        {
            using (XmlReader reader = XmlReader.Create(stream))
            {
                return XDocument.Load(reader);
            }
        }

}
}

No comments:

Post a Comment