如何使用XmlReader类?
我想使用XmlReader保存并加载我的xml数据。 但我不知道如何使用这个课程。 你能给我一个开始的示例代码吗?
我个人已经从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 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 ();
现在它可以传递并使用我的对象类的任何固有函数进行操作。
为方便起见,我的类具有将自身创建为xml节点的function。
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; }
MSDN有一个简单的例子可以帮助您入门。
如果您对阅读和编写XML文档感兴趣,而不仅仅是专门使用XmlReader类,那么这里有一篇很好的文章介绍了一些选项 。
但是如果你只想开始玩游戏,试试这个:
XmlReaderSettings settings = new XmlReaderSettings(); settings.IgnoreWhitespace = true; settings.IgnoreComments = true; XmlReader reader = XmlReader.Create("file.xml", settings);
您应该使用Create
方法而不是new
,因为XmlReader
是使用Factory模式的abstract class
。
var xmlReader = XmlReader.Create("xmlfile.xml");
从Nutshell中出色的C#3.0开始 ,请考虑查看第11章中的示例代码 。
上述就是C#学习教程:如何使用XmlReader类?分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/951317.html