C#

C# XML序列化

Posted by Kerwen Blog on January 3, 2020
  1. Open xml to copy xml content
  2. Create a new class in VS
  3. Edit -> Paste Special -> Paste XML as Classes

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    
     [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
     [System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
     public partial class Server
     {
    
         private string uriField;
    
         /// <remarks/>
         public string uri
         {
             get
             {
                 return this.uriField;
             }
             set
             {
                 this.uriField = value;
             }
         }
     }
    
  4. Read xml data

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    
     private Server GetServerListFromXML()
     {
         XmlDocument xmlDoc = new XmlDocument();
         string strXML = GetConfigXmlPath();
         if (!File.Exists(strXML))
         {
             Logger.Instance().LogError("XML File: " + strXML + " is NOT existed.");
             return null;
         }
         try
         {
             xmlDoc.Load(strXML);
         }
         catch (Exception e)
         {
             Logger.Instance().LogError("Cannot load " + strXML + ". Error message: " + e.Message);
         }
         Server serversList = ParseXML.DeserializeXML<Server>(xmlDoc.OuterXml);
         return serversList;
     }
    
  5. Save data to xml

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    
     private bool SaveServiceAddress(Server info)
     {
         StreamWriter sw = null;    
         try
         {
             string xml = ParseXML.Serializer(typeof(Server), info);
             string strXML = GetConfigXmlPath();
             FileStream fs = new FileStream(strXML, FileMode.OpenOrCreate);
             sw = new StreamWriter(fs);
             sw.Write(xml);
             sw.Close();
         }
         catch (Exception e)
         {
             if (sw != null)
             {
                 sw.Close();
             }
             return false;
         }
         return true;
     }