[C#] C#简单的 XmlSerializer 用法范例 →→→→→进入此内容的聊天室

来自 , 2019-10-12, 写在 C#, 查看 179 次.
URL http://www.code666.cn/view/d290dc6c
  1. // This is the test class we want to
  2. // serialize:
  3. [Serializable()]
  4. public class TestClass
  5. {
  6.     private string someString;
  7.     public string SomeString
  8.     {
  9.         get { return someString; }
  10.         set { someString = value; }
  11.     }
  12.  
  13.     private List<string> settings = new List<string>();
  14.     public List<string> Settings
  15.     {
  16.         get { return settings; }
  17.         set { settings = value; }
  18.     }
  19.  
  20.     // These will be ignored
  21.     [NonSerialized()]
  22.     private int willBeIgnored1 = 1;
  23.     private int willBeIgnored2 = 1;
  24.  
  25. }
  26.  
  27. // Example code
  28.  
  29. // This example requires:
  30. // using System.Xml.Serialization;
  31. // using System.IO;
  32.  
  33. // Create a new instance of the test class
  34. TestClass TestObj = new TestClass();
  35.  
  36. // Set some dummy values
  37. TestObj.SomeString = "foo";
  38.  
  39. TestObj.Settings.Add("A");
  40. TestObj.Settings.Add("B");
  41. TestObj.Settings.Add("C");
  42.  
  43.  
  44. #region Save the object
  45.  
  46. // Create a new XmlSerializer instance with the type of the test class
  47. XmlSerializer SerializerObj = new XmlSerializer(typeof(TestClass));
  48.  
  49. // Create a new file stream to write the serialized object to a file
  50. TextWriter WriteFileStream = new StreamWriter(@"C:\test.xml");
  51. SerializerObj.Serialize(WriteFileStream, TestObj);
  52.  
  53. // Cleanup
  54. WriteFileStream.Close();
  55.  
  56. #endregion
  57.  
  58.  
  59. /*
  60. The test.xml file will look like this:
  61.  
  62. <?xml version="1.0"?>
  63. <TestClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  64.   <SomeString>foo</SomeString>
  65.   <Settings>
  66.     <string>A</string>
  67.     <string>B</string>
  68.     <string>C</string>
  69.   </Settings>
  70. </TestClass>             
  71. */
  72.  
  73. #region Load the object
  74.  
  75. // Create a new file stream for reading the XML file
  76. FileStream ReadFileStream = new FileStream(@"C:\test.xml", FileMode.Open, FileAccess.Read, FileShare.Read);
  77.  
  78. // Load the object saved above by using the Deserialize function
  79. TestClass LoadedObj = (TestClass)SerializerObj.Deserialize(ReadFileStream);
  80.  
  81. // Cleanup
  82. ReadFileStream.Close();
  83.  
  84. #endregion
  85.  
  86.  
  87. // Test the new loaded object:
  88. MessageBox.Show(LoadedObj.SomeString);
  89.  
  90. foreach (string Setting in LoadedObj.Settings)
  91.     MessageBox.Show(Setting);
  92. //csharp/2052

回复 "C#简单的 XmlSerializer 用法范例"

这儿你可以回复上面这条便签

captcha