Search code examples
c#xmlxmlreader

How to use XmlReader class?


I want to save and load my xml data using XmlReader. But I don't know how to use this class. Can you give me a sample code for start?


Solution

  • Personally I have switched away from XMLReader to System.XML.Linq.XDocument to manage my XML data files. This way I can easily pull data from xml into objects and manage them like any other object in my program. When I am done manipulating them I can just save the changes back out the the xml file at any time.

            //Load my xml document
            XDocument myData = XDocument.Load(PhysicalApplicationPath + "/Data.xml");
    
            //Create my new object
            HelpItem newitem = new HelpItem();
            newitem.Answer = answer;
            newitem.Question = question;
            newitem.Category = category;
    
            //Find the Parent Node and then add the new item to it.
            XElement helpItems = myData.Descendants("HelpItems").First();
            helpItems.Add(newitem.XmlHelpItem());
    
            //then save it back out to the file system
            myData.Save(PhysicalApplicationPath + "/Data.xml");
    

    If I want to use this data in an easily managed data set I can bind it to a list of my objects.

            List<HelpItem> helpitems = (from helpitem in myData.Descendants("HelpItem")
                      select new HelpItem
                      {
                           Category = helpitem.Element("Category").Value,
                           Question = helpitem.Element("Question").Value,
                           Answer = helpitem.Element("Answer").Value,
                      }).ToList<HelpItem>();
    

    Now it can be passed around and manipulated with any inherent functions of my object class.

    For convenience my class has a function to create itself as an xml node.

    public XElement XmlHelpItem()
        {
            XElement helpitem = new XElement("HelpItem");
            XElement category = new XElement("Category", Category);
            XElement question = new XElement("Question", Question);
            XElement answer = new XElement("Answer", Answer);
            helpitem.Add(category);
            helpitem.Add(question);
            helpitem.Add(answer);
            return helpitem;
        }