2009-05-24 59 views
13

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

+3

71000结果从http://www.google.ca/search?hl=en&q=xmlreader+example – ChrisW 2009-05-24 17:40:34

+26

是的,但是这就是StackOverflow的是,太! – Unsliced 2009-07-15 16:24:11

+1

XmlReader是POCO Entites tt用来读取edmx文件的读取器。因此,为了继续使用他们的API并正确使用它,而不是自己解析emdx文件,我需要使用XmlReader。 – 2012-08-22 11:57:01

回答

8

个人而言,我已经从切换的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>(); 

现在可以通过我的对象类的任何固有函数来传递和操纵它。

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

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

,您应该使用Create方法,而不是使用new,因为XmlReaderabstract class使用the Factory pattern

var xmlReader = XmlReader.Create("xmlfile.xml"); 
+0

这应该被接受为这个问题的真正答案。 – 2013-07-26 13:56:25

12

MSDN看sample code有一个简单的例子,让你开始here

如果您有兴趣阅读和编写XML文档,而不仅仅是专门使用XmlReader类,则有a nice article covering a few of your options here

但如果你只是想开始和玩,试试这个:

XmlReaderSettings settings = new XmlReaderSettings(); 
settings.IgnoreWhitespace = true; 
settings.IgnoreComments = true; 
XmlReader reader = XmlReader.Create("file.xml", settings);