Spot the web RSS 2.0
# Thursday, December 20, 2007

If you want to store configuration information in a XML file, you can easily use serialization to assist you. Instead of using XPath or DOM, and have some code to maintain, simply use the XmlSerializer to retrieve information.

Here's an example of a XML file:

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <DatabaseConfig>
  3.   <Data>
  4.     <DatabaseConfigData
  5.       File="Data/Principal.xml"
  6.       EntityName="Principal"
  7.       Format="Xml" />
  8.     <DatabaseConfigData
  9.       File="Data/Role.xml"
  10.       EntityName="Role"
  11.       Format="Xml" />
  12.   </Data>
  13. </DatabaseConfig>

 

And if you have the following classes (C#):

  1. public class DatabaseConfig
  2. {
  3.     public DatabaseConfigData[] Data { get; set; }
  4. };
  5.  
  6. public class DatabaseConfigData
  7. {
  8.     [System.Xml.Serialization.XmlAttribute()]
  9.     public string File { get; set; }
  10.  
  11.     [System.Xml.Serialization.XmlAttribute()]
  12.     public string EntityName { get; set; }
  13.  
  14.     [System.Xml.Serialization.XmlAttribute()]
  15.     public string Format { get; set; }
  16. };

 

All you have to do to load the XML information into the DatabaseConfig class is (C#):

  1. DatabaseConfig GetDatabaseConfig(string file)
  2. {
  3.     XmlSerializer serializer =
  4.         new XmlSerializer(typeof(DatabaseConfig));
  5.     using (StreamReader reader = new StreamReader(file))
  6.     {
  7.         object obj = serializer.Deserialize(reader);
  8.         return (DatabaseConfig)obj;
  9.     }
  10. }

There are a few issues you have to handle when using XML Serialization, wich you can see at my earlier posts about XMLXSD and Serialization.

Thursday, December 20, 2007 6:35:13 PM (Jerusalem Standard Time, UTC+02:00)  #    Comments [0] - Trackback
.Net | Programming | Serialization | XML
Comments are closed.
Navigation
Archive
<July 2010>
SunMonTueWedThuFriSat
27282930123
45678910
11121314151617
18192021222324
25262728293031
1234567
About the author/Disclaimer

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

© Copyright 2010
Guy Levin
Sign In
Statistics
Total Posts: 63
This Year: 0
This Month: 0
This Week: 0
Comments: 14
Themes
All Content © 2010, Guy Levin