将对象序列化到XML存储库中 [英] Serializing objects into XML repository

查看:23
本文介绍了将对象序列化到XML存储库中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我喜欢XmlSerializer,因为它具有即发即忘的操作。我可以向XmlSerializer提供要序列化的对象和要序列化到的文件,XmlSerializer将对属性名称和值进行排序。

XmlWriter xmlWriter = XmlWriter.Create(projectPath + "\" + m_projectDescriptionFileName);  // create new project description file (XML)
XmlSerializer xmlSerializer = new XmlSerializer(typeof(CustomerContactInfoViewModel));
xmlSerializer.Serialize(xmlWriter, contactInfo);
xmlWriter.Close();

我喜欢LINQ to XML的导航功能。以下是一个用于编辑存储在XML(改编自Greg's blog)中的对象的方法示例。还有用于插入和删除的代码段。)

public void EditBilling(Billing billing)
{
    XElement node = m_billingData.Root.Elements("item").Where(i => (int)i.Element("id") == billing.ID).FirstOrDefault();

    node.SetElementValue("customer", billing.Customer);
    node.SetElementValue("type", billing.Type);
    node.SetElementValue("date", billing.Date.ToShortDateString());
    node.SetElementValue("description", billing.Description);
    node.SetElementValue("hours", billing.Hours);

    m_billingData.Save(HttpContext.Current.Server.MapPath("~/App_Data/Billings.xml"));
}

如您所见,与XmlSerializer不同,属性名称和值是在代码中写出的。

我希望能够在同一个XML文件中存储多个不同类型的对象(在不同的时间添加它们,而不是一次全部添加)。我希望能够一次一个地反序列化它们。我想一次更新一个。

  • 有没有办法将LINQ导航与XmlSerializer的即发即忘功能结合起来?
  • XmlSerializer是不是合适的工具?
  • 有没有更好的(除了设置合适的数据库)?
  • 我要找的是不同名称的内容吗?

我们非常感谢您的任何建议、见解或参考!

推荐答案

使用XmlSerializer不会直接允许您将多个不同类型的对象序列化到同一文件中。在使用XmlSerializer之前,您需要稍微调整一下对XML文件的读取。

您有两个选择。

选项1:

第一个是您有一个包装类,如注释中所建议的,它保存您的对象。然后,您可以使用XmlSerializer来序列化/反序列化该特定类型。您不能直接选取XML的一部分并将其序列化。这将允许您直接序列化和反序列化整个类型/类。

快速样本:

public class Container {
    public MyType My {get;set;}
    public OtherType Other {get;set;}
}

Container container = new Container();
...
XmlSerializer serializer = new XmlSerializer(typeof(Container));
serializer.Serialize(aWriter, container);

// deserialize

StreamReader reader = new StreamReader("container.xml");
Container c = serializer.Deserialize(reader) as Container;

选项2:

可以使用XmlReader读取XML文件,然后使用ReadToDecendant(string)查找对象的当前XML表示形式(让我们称之为MyType),并使用ReadSubTree()读取该XML。使用ReadSubTree()的结果并将其推送到XmlSerializer.Deserialize()方法。

快速样本如下所示:

XmlReader reader = XmlReader.Create("objects.xml");
if (reader.ReadToDecendant("MyType"))
{
    var myTypeXml = reader.ReadSubTree(); // read the whole subtree  (type)
    XmlSerializer serializer = new XmlSerializer(typeof(MyType)); // define the type
    MyType obj = serializer.Deserialize(myTypeXml); // 
}

写入对象是另一种方法,将类型序列化()为(XML)字符串,然后替换文件中相应的XML。

您最好使用数据库作为数据存储,而不是使用XML。我希望您有一个使用文件而不是数据库的好理由。

选项2可能是最合适和最灵活的实现,因为它不依赖包装类。

这篇关于将对象序列化到XML存储库中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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