- Open xml to copy xml content
- Create a new class in VS
-
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; } } } -
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; } -
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; }