简体   繁体   English

将多个自定义对象序列化和反序列化为XML

[英]Serialize and deserialize multiple custom objects to XML

I have to serialize multiple custom objects like Customer, Store, etc. Each object has just properties, and objects no relationship with each other. 我必须序列化多个自定义对象,例如Customer,Store等。每个对象只有属性,而对象之间没有关系。 I have to serialize to XML, and deserialize back to custom objects. 我必须序列化为XML,然后反序列化为自定义对象。

How can I do this in C# ? 如何在C#中做到这一点?

Generate the xsd as follows: 生成xsd,如下所示:

 "$(Registry:HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SDKs\Windows\v7.0A\@InstallationFolder)\bin\xsd.exe" /n:"$(ProjectName).Namespace" "$(ProjectDir)\<YourXML>" 

This should be a 1 times thing since your validation will stay constant. 这应该是1次,因为您的验证将保持不变。

create a prebuild event in your project for generating the class as follows: 在项目中创建一个预生成事件以生成类,如下所示:

<PreBuildEvent>
  "$(Registry:HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SDKs\Windows\v7.0A\@InstallationFolder)\bin\xsd.exe" /n:"$(ProjectName).Namespace" "$(ProjectDir)\<YourXSD>" /c /o:"$(ProjectDir)\<GeneratedClassFolder>"
</PreBuildEvent>

Then you can use the built in .NET XMLSerializer to write your classes to an XML file. 然后,您可以使用内置的.NET XMLSerializer将您的类写入XML文件。

You can make an XSD file defining your classes. 您可以制作一个XSD文件来定义您的类。 Then you can use the built in .NET XMLSerializer to write your classes to an XML file. 然后,您可以使用内置的.NET XMLSerializer将您的类写入XML文件。 You can use the XSD to validate your inputs during deserialization. 您可以使用XSD在反序列化期间验证输入。

Or you can apply the Serializable attribute for your classes. 或者,您可以为您的类应用Serializable属性。

a quick google reveals this article on Switch On The code with examples on how to serialize and deserialize to XML. 一位快速的google在“开启代码上揭示了这篇文章 ,并提供了有关如何序列化和反序列化为XML的示例。 here is an code example on serializing and deserializing an object. 这是有关序列化和反序列化对象的代码示例。

static public void SerializeToXML<_type>(_type item,string fileName)
{
  XmlSerializer serializer = new XmlSerializer( item.GetType() );
  TextWriter textWriter = new StreamWriter( fileName );
  serializer.Serialize(textWriter, item);
  textWriter.Close();
}

static _type DeserializeFromXML<_type>(string fileName)
{
   XmlSerializer deserializer = new XmlSerializer(typeof(_type));
   TextReader textReader = new StreamReader( fileName );

   _type item = (_type)deserializer.Deserialize(textReader);
   textReader.Close();

   return item;
}

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

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