简体   繁体   English

如何从Xml文件存储和检索对象

[英]How to store and retrieve objects from Xml file

I have this class: 我有这个课:

public class MyMenu
{
    public string Name { get; set; }
    public string Type { get; set; }
}

This class I want to use it in a dynamic menu, and I do not want to store his data in a database. 我想在动态菜单中使用该类,并且我不想将其数据存储在数据库中。

I want to store its data in Xml file. 我想将其数据存储在Xml文件中。

Till now I have this for saving data: 到现在为止,我有这个用于保存数据:

string path = Server.MapPath("~/Content/Files");
XmlSerializer serial = new XmlSerializer(model.GetType());
System.IO.StreamWriter writer = new System.IO.StreamWriter(path + "\\ribbonmenu");
serial.Serialize(writer, model);
writer.Close();

And this to get the data: 这是为了获取数据:

string path = Server.MapPath("~/Content/Files");
XmlSerializer serial = new XmlSerializer(typeof(RibbonMenu));
System.IO.StreamReader reader = new System.IO.StreamReader(path + "\\ribbonmenu");          
RibbonMenu menu =(RibbonMenu) serial.Deserialize(reader);
reader.Close();

What I have is working for one object to save and get. 我正在为一个对象进行保存和获取。 I need to save multiple objects, and get the collection of objects, something like: 我需要保存多个对象,并获取对象的集合,例如:

IEnumerable<MyMenu> model=(IEnumerable<MyMenu>) serial.Deserialize(reader);

Can someone give me a solution? 有人可以给我解决方案吗? Thanks. 谢谢。

Edit: The content of the generated Xml with my code is: 编辑:用我的代码生成的Xml的内容是:

<?xml version="1.0" encoding="utf-8"?>
<MyMenu xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Id>0</Id>
  <Menu>Home</Menu>
  <Type>Button</Type>

</MyMenu>

When serializing you should initialize a collection like this: 序列化时,您应该像这样初始化一个集合:

var model = new List<MyMenu>()
{
    new MyMenu() { Name = "Menu1", Type = "Ribbon" },
    new MyMenu() { Name = "Menu2", Type = "Ribbon" },
};

This way, when you serialize you'd get something like this: 这样,当您进行序列化时,您将得到以下内容:

<?xml version="1.0" encoding="utf-8"?>
<ArrayOfMyMenu xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <MyMenu>
    <Name>Menu1</Name>
    <Type>Ribbon</Type>
  </MyMenu>
  <MyMenu>
    <Name>Menu2</Name>
    <Type>Ribbon</Type>
  </MyMenu>
</ArrayOfMyMenu>

And you can get the object back by using List as the type of serializer: 您可以通过使用List作为序列化器的类型来找回对象:

XmlSerializer serial = new XmlSerializer(typeof(List<MyMenu>));
System.IO.StreamReader reader = new System.IO.StreamReader("ribbonmenu.xml");
var menu = (List<MyMenu>)serial.Deserialize(reader);
reader.Close(); 

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM