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?
You should use the Create
method instead of using new
, since XmlReader
is an abstract class
using the Factory pattern.
var xmlReader = XmlReader.Create("xmlfile.xml");
From the excellent C# 3.0 in a Nutshell, consider looking at the sample code from chapter 11.
MSDN has a simple example to get you started here.
If you're interested in reading and writing XML documents, and not just specifically using the XmlReader class, there's a nice article covering a few of your options here.
But if you just want to get started and play around, try this:
XmlReaderSettings settings = new XmlReaderSettings();
settings.IgnoreWhitespace = true;
settings.IgnoreComments = true;
XmlReader reader = XmlReader.Create("file.xml", settings);
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;
}