我想使用XmlReader保存和加载我的xml数据。但是我不知道如何使用这个类。你能给我一个样例代码吗?
我想使用XmlReader保存和加载我的xml数据。但是我不知道如何使用这个类。你能给我一个样例代码吗?
MSDN有一个简单的示例可供您开始学习,在这里。
如果您对读写XML文档感兴趣,而不仅仅是使用XmlReader类,这里有一篇不错的文章介绍了您的一些选择。
但如果您只是想开始尝试并进行实验,请尝试这个:
XmlReaderSettings settings = new XmlReaderSettings();
settings.IgnoreWhitespace = true;
settings.IgnoreComments = true;
XmlReader reader = XmlReader.Create("file.xml", settings);
就我个人而言,我已经从XMLReader转向使用System.XML.Linq.XDocument来管理我的XML数据文件。这样我可以轻松地将数据从xml中提取出来,并像程序中的任何其他对象一样进行管理。当我完成操作后,我可以随时将更改保存回xml文件中。
//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");
如果我想将这些数据绑定到一个易于管理的数据集中,我可以将其绑定到我的对象列表。
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>();
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;
}
由于XmlReader
是使用工厂模式的抽象类
,因此您应该使用Create
方法而不是使用new
。
var xmlReader = XmlReader.Create("xmlfile.xml");