将对象序列化为XML存储库

时间:2015-02-22 00:02:53

标签: .net xml serialization crud

我喜欢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是一种正确的工具吗?
  • 有没有更好的东西(没有建立适当的数据库)?
  • 我在找一些不同名字的东西吗?

任何建议,见解或参考都非常感谢!

1 个答案:

答案 0 :(得分:0)

使用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)并读取该xml使用ReadSubTree()。使用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); // 
}

编写对象将是相反的方式,将类型Serialize()转换为(xml)字符串,然后替换文件中的相应xml。

使用数据库作为数据存储而不是xml会更好。我希望你有充分的理由使用文件而不是数据库。

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

相关问题