XML Manager - read and write XML-files

If you want to use XML structures in your project you need to read and create XML files. For this I got a class called XMLManager. The only thing you need for this is a shema of the XML structur you want to read or create.


With this class you can write or read attributes to or from XML files. If you included your shema file in your project you can call its XML tags as classes and fill them with values or read the values. The DeserializeFile filles those classes and the SerializeToFile writes them down in a file.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class XMLManager
{
 //read XML files
 public T DeserializeFile<T>(string filename)
 {
  //call a reader
  TextReader reader = new StreamReader(filename);
  XmlSerializer serializer = new XmlSerializer(typeof(T));
  //read the values out of the xml file and create with the values an object 
  T import = (T)serializer.Deserialize(reader);
  reader.Close();
  return import;
 }
 
 //create xml files
 public void SerializeToFile<T>(T xmlObject, string filename)
 {
  //create a file
  Stream fs = new FileStream(filename, FileMode.Create);
  //call a writer
  XmlWriterSettings settings = new XmlWriterSettings();
  settings.Indent = true;
  settings.Encoding = Encoding.Unicode;
  settings.NewLineChars = Environment.NewLine;
  //read all values out of the object
  XmlWriter writer = XmlWriter.Create(fs, settings);
  XmlSerializer serializer = new XmlSerializer(typeof(T));
  //write the xml structure within the values down
  serializer.Serialize(writer, xmlObject);
  writer.Close();
  fs.Close();
 }
}

Comments

Popular posts from this blog

How to support multiple languages in WPF