如何使用XmlReader类? [英] How to use XmlReader class?

查看:264
本文介绍了如何使用XmlReader类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要保存和使用的XmlReader加载我的XML数据。但我不知道如何使用这个类。你能给我一个示例代码开始?

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?

推荐答案

我个人从切换的XMLReader客场System.XML.Linq.XDocument管理我的XML数据文件。这样我可以很容易地拉离XML数据转换对象和管理他们像在我的计划中任何其他对象。当我做了操纵他们,我可以只保存更改背出XML文件在任何时候。

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.

为了方便我班有一个函数来创建自己作为一个XML节点。

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;
    }

这篇关于如何使用XmlReader类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆