Deserialize XML file with objects to Array - c#

This is my code so far:
using System;
using System.Collections;
using System.Linq;
using System.Text;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using System.Xml.Serialization;
using System.Collections.Generic;
using System.Xml;
namespace Opgaver
{
class OpgaveController
{
static ArrayList _arrAktiveOpgaver = new ArrayList();
public ArrayList arrAktiveOpgaver
{
get { return _arrAktiveOpgaver; }
set { _arrAktiveOpgaver = value; }
}
static ArrayList _arrAfsluttedeOpgaver = new ArrayList();
public ArrayList arrAfsluttedeOpgaver
{
get { return _arrAfsluttedeOpgaver; }
set { _arrAfsluttedeOpgaver = value; }
}
static int _opgavenr = 100;
public int opgavenr
{
get { return _opgavenr; }
set { _opgavenr = value; }
}
public void opretOpgave(string opgavenavn, string opgavebeskrivelse, int opgaveprioritet, DateTime opgaveafsluttetdato)
{
DateTime oprettetdato = new DateTime();
oprettetdato = DateTime.Now;
bool opgaveafsluttet = false;
Opgave opgave = new Opgave(oprettetdato, _opgavenr, opgavenavn, opgavebeskrivelse, opgaveprioritet, opgaveafsluttet, opgaveafsluttetdato);
if (opgave.opgaveAfsluttet == false)
{
_arrAktiveOpgaver.Add(opgave);
}
else
{
_arrAfsluttedeOpgaver.Add(opgave);
}
_opgavenr++;
}
public OpgaveController()
{
}
}
public void test()
{
string outfile = #"C:\Folder\Tester.xml";
XmlSerializer xs;
Serialize<List<Opgave>>(arrAktiveOpgaver, outfile);
arrAktiveOpgaver = <List<Opgave>>(outfile);//deserialize data - Generates this error: Error 2 Using the generic type 'System.Collections.Generic.List<T>' requires 1 type arguments P:\Programmerings opgaver\Opgaver\Opgaver\OpgaveController.cs 107 33 Opgaver
}
private void Serialize<T1>(ArrayList arrAktiveOpgaver, string outfile)
{
throw new NotImplementedException();
}
public static T DeserializeFromXml<T>(string inputFile)
{
XmlSerializer s = new XmlSerializer(typeof(T));
T deserializedObject = default(T);
using (TextReader textReader = new StreamReader(inputFile))
{
deserializedObject = (T)s.Deserialize(textReader);
textReader.Close();
}
return deserializedObject;
}
public static void SerializeToXml<T>(T objToSerialize, string outputFile)
{
XmlSerializer s = new XmlSerializer(objToSerialize.GetType());
using (TextWriter textWriter = new StreamWriter(outputFile))
{
s.Serialize(textWriter, objToSerialize);
textWriter.Close();
}
}
}
}
i need to serialize the arraylist, and deserialize it..
and here is my opgave class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Opgaver
{
[Serializable()] public class Opgave : IComparable
{
DateTime _oprettetDato = new DateTime();
public DateTime oprettetDato
{
get { return _oprettetDato; }
set { _oprettetDato = value; }
}
int _opgavenr;
public int opgavenr
{
get { return _opgavenr; }
set { _opgavenr = value; }
}
string _opgaveNavn;
public string opgaveNavn
{
get { return _opgaveNavn; }
set { _opgaveNavn = value; }
}
string _opgaveBeskrivelse;
public string opgaveBeskrivelse
{
get { return _opgaveBeskrivelse; }
set { _opgaveBeskrivelse = value; }
}
int _opgavePrioritet;
public int opgavePrioritet
{
get { return _opgavePrioritet; }
set { _opgavePrioritet = value; }
}
bool _opgaveAfsluttet = false;
public bool opgaveAfsluttet
{
get { return _opgaveAfsluttet; }
set { _opgaveAfsluttet = value; }
}
DateTime _opgaveAfsluttetDato = new DateTime();
public DateTime opgaveAfsluttetDato
{
get { return _opgaveAfsluttetDato; }
set { _opgaveAfsluttetDato = value; }
}
public Opgave()
{
}
public Opgave(DateTime oprettetdato, int opgavenr, string opgavenavn, string opgavebeskrivelse, int opgaveprioritet, bool opgaveafsluttet, DateTime opgaveafsluttetdato)
{
_oprettetDato = oprettetdato;
_opgavenr = opgavenr;
_opgaveNavn = opgavenavn;
_opgaveBeskrivelse = opgavebeskrivelse;
_opgavePrioritet = opgaveprioritet;
_opgaveAfsluttet = opgaveafsluttet;
_opgaveAfsluttetDato = opgaveafsluttetdato;
}
//Sorterings metode
public int CompareTo(object obj)
{
Opgave Compare = (Opgave)obj;
int result = this.opgavenr.CompareTo(Compare.opgavenr);
if (result == 0)
result = this.opgavenr.CompareTo(Compare.opgavenr);
return result;
}
}
}

Use this static methods whenver you want to serialize or deserialize data:
example:
public void test()
{
string outfile = #"C:\Folder\Tester.xml";
SerializeToXml<List<Opgaver>>(arrAktiveOpgaver, outfile);//serialize data
arrAktiveOpgaver = DeserializeFromXml<List<Opgaver>>(outfile);//deserialize data
}
public static T DeserializeFromXml<T>(string inputFile)
{
XmlSerializer s = new XmlSerializer(typeof(T));
T deserializedObject = default(T);
using (TextReader textReader = new StreamReader(inputFile))
{
deserializedObject = (T)s.Deserialize(textReader);
textReader.Close();
}
return deserializedObject;
}
public static void SerializeToXml<T>(T objToSerialize, string outputFile)
{
XmlSerializer s = new XmlSerializer(objToSerialize.GetType());
using (TextWriter textWriter = new StreamWriter(outputFile))
{
s.Serialize(textWriter, objToSerialize);
textWriter.Close();
}
}

Serialize array of Opgave instead of serializing them in loop.
XmlSerializer xs = new XmlSerializer(arrAktiveOpgaver.GetType());
xs.Serialize(sw, arrAktiveOpgaver);
And then deserialize as array of Opgave.

Related

dictionaryApp,MVVM,WPF,reading from textFile

i am building a dictionary WPF application where you write a word and than the application tells u in what language the word is and also gives you a description of the word. Using MVVM.
Here is how it looks:
I have problem with finding out how to get the language and the description of word from a text file and put them in the text box, i dont mean the binding, but the exact method of getting the info.
Here is my Model:
using System;
using System.Collections.ObjectModel;
using System.Collections.Generic;
namespace dictionary
{
public class dictionaryModel
{
private string word;
private string language;
private string description;
public string Word
{
get
{
return word;
}
set
{
word = value;
}
}
public string Language
{
get
{
return language;
}
set
{
language = value;
}
}
public string Description
{
get
{
return description;
}
set
{
description = value;
}
}
public dictionaryModel(string describedWord, string WordLanguage, string WordDescription)
{
this.word = describedWord;
this.language = WordLanguage;
this.description = WordDescription;
}
public dictionaryModel()
{ }
}
and here is my View Model, so far:
namespace dictionary
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Markup;
public class dictionaryViewModel : INotifyPropertyChanged
{
private ICommand _getAnswer;
private dictionaryModel m;
private string w;
private string retLanguage;
private string retDescription;
private bool _canExecute;
public dictionaryViewModel()
{
_canExecute = true;
}
public string retLang
{
get
{
return retLanguage;
}
set
{
retLanguage = value;
NotifyPropertyChanged();
}
}
public string retDescr
{
get
{
return retDescription;
}
set
{
retDescription = value;
NotifyPropertyChanged();
}
}
public string word
{
get
{
return w;
}
set
{
w = value;
NotifyPropertyChanged();
}
}
public dictionaryModel model
{
get
{
return m;
}
set
{
m = value;
NotifyPropertyChanged();
}
}
public ICommand getAnswer
{
get
{
return _getAnswer ?? (_getAnswer = new RelayCommand(() => getWholeAnswer(word), _canExecute));
}
}
public dictionaryViewModel(dictionaryModel model, string word, string retLang, string retDescr,
ICommand getAnswer)
{
m = model;
w = word;
retLang = retLanguage;
retDescr = retDescription;
_getAnswer = getAnswer;
}
public ObservableCollection<dictionaryModel> readTxtFile()
{
ObservableCollection<dictionaryModel> dictObj = new ObservableCollection<dictionaryModel>();
string word;
string language;
string description;
var file = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), "dictionary.txt");
StreamReader read = new StreamReader(file);
string line;
string[] item;
while((line=read.ReadLine())!=null)
{
item = line.Split(';');
word = item[0];
language = item[1];
description = item[2];
dictionaryModel object1 = new dictionaryModel(word, language, description);
dictObj.Add(object1);
}
read.Close();
return dictObj;
}
public void getWholeAnswer(string w)
{
string descr, lang;
dictionaryModel obj = null;
ObservableCollection<dictionaryModel> rdF = readTxtFile();
try
{
foreach(dictionaryModel a in rdF)
{
if(w.Equals(a))
{
descr = retDescr;
lang = retLang;
obj = a;
}
obj.Language = retLang;
obj.Description = retDescription;
}
}catch(Exception e)
{
ExceptionInfo();
}
}
private void ExceptionInfo()
{
throw new NotImplementedException();
}
private void NotifyPropertyChanged()
{
throw new NotImplementedException();
}
public event PropertyChangedEventHandler PropertyChanged;
}
}
The method is getWholeAnswer(). You see what i have tried, but no success. If you have any ideas, please help me out...
I think the problem is here:
if(w.Equals(a))
w is a string, while a is dictionaryModel, you are comparing two different kind of types without defining an equality logic.
Maybe you would replace that line with this?
if(string.Compare(w.Trim(), a.word, true) == 0)
string.Compare reference on MSDN
string.Trim reference on MSDN
i found my mistake, i am posting the solution of the method, it could be helpful to someone:
public void getWholeAnswer(string w)
{
dictionaryModel obj = null;
ObservableCollection<dictionaryModel> rdF = readTxtFile();
bool find = false;
try
{
foreach(dictionaryModel a in rdF)
{
if(w.Equals(a.Word))
{
obj = a;
retLang = a.Language;
retDescr = a.Description;
find = true;
break;
}
}
if(false == find)
{
AskTheQuestion();
}
}catch(Exception e)
{
AskTheQuestion();
}
}

Unable to deserialize an encrypted array in c#

The following code in my program serializes, encrypts and writes the byte array to disk. From the looks of it, the encryption works fine. The issue arises when the program decrypts and then deserializes the file.
Visual Studio displays the following error:
'System.Runtime.Serialization.SerializationException' occurred in System.Runtime.Serialization.dll
Additional information: There was an error deserializing the object of type Test.Store. The data at the root level is invalid.
I've been stuck on this one for two days, so any help would be greatly appreciated!
The following code has been trimmed down from its original form:
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using System.Security.Cryptography;
using System.Text;
namespace Test
{
public class K
{
#region Non-Public Data Members
private string _n = string.Empty;
private string _u = string.Empty;
private string _p = string.Empty;
private string _u2 = null;
private string _n2 = string.Empty;
public K()
{
}
public string T
{
get { return _n; }
set { _n = value; }
}
public string U
{
get { return _u; }
set { _u = value; }
}
public string P
{
get { return _p; }
set { _p = value; }
}
public string U2
{
get { return _u2; }
set { _u2 = value; }
}
public string N2
{
get { return _n2; }
set { _n2 = value; }
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
//stuff
return sb.ToString();
}
#endregion
}
public class Group
{
private string _text = string.Empty;
private int _imageIndex = 0;
private List<K> _credentials = new List<K>();
public Group()
{
}
public Group(string text, int imageIndex)
{
_text = text;
_imageIndex = imageIndex;
}
public string Text
{
get { return _text; }
set { _text = value; }
}
public int ImageIndex
{
get { return _imageIndex; }
set { _imageIndex = value; }
}
public List<K> Ks
{
get { return _credentials; }
set { _credentials = value; }
}
public override string ToString()
{
return Text;
}
}
public class Store
{
private List<Group> _groups = new List<Group>();
private string _docname = string.Empty;
private bool _dirtyBit = false;
public bool DirtyBit
{
get { return _dirtyBit; }
set { _dirtyBit = value; }
}
public List<Group> Groups
{
get { return _groups; }
set { _groups = value; }
}
public string DocName
{
get { return _docname; }
set { _docname = value; }
}
}
public class Crypto
{
public static string secretKey = "abcdefgh";
[System.Runtime.InteropServices.DllImport("KERNEL32.DLL", EntryPoint = "RtlZeroMemory")]
public static extern bool ZeroMemory(ref string Destination, int Length);
static string GenerateKey()
{
DESCryptoServiceProvider desCrypto = (DESCryptoServiceProvider)DESCryptoServiceProvider.Create();
return ASCIIEncoding.ASCII.GetString(desCrypto.Key);
}
public static byte[] PerformCrypto(ICryptoTransform cryptoTransform, byte[] data)
{
using (var memoryStream = new MemoryStream())
{
using (var cryptoStream = new CryptoStream(memoryStream, cryptoTransform, CryptoStreamMode.Write))
{
cryptoStream.Write(data, 0, data.Length);
cryptoStream.FlushFinalBlock();
return memoryStream.ToArray();
}
}
}
public static byte[] Decrypt(byte[] cipherTextBytes)
{
DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
DES.Key = ASCIIEncoding.ASCII.GetBytes(secretKey);
DES.IV = ASCIIEncoding.ASCII.GetBytes(secretKey);
using (var decryptor = DES.CreateDecryptor(DES.Key, DES.IV))
{
return PerformCrypto(decryptor, cipherTextBytes);
}
}
public static byte[] Encrypt(byte[] plainTextBytes)
{
DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
DES.Key = ASCIIEncoding.ASCII.GetBytes(secretKey);
DES.IV = ASCIIEncoding.ASCII.GetBytes(secretKey);
using (var encryptor = DES.CreateEncryptor(DES.Key, DES.IV))
{
return PerformCrypto(encryptor, plainTextBytes);
}
}
}
public static class StoreMgr
{
private static Store _doc = new Store();
public static void FileSaveAs(string fn)
{
using (MemoryStream ms = new MemoryStream())
{
DataContractSerializer serializer = new DataContractSerializer(typeof(Store));
serializer.WriteObject(ms, _doc);
byte[] byteArrayInput = ms.GetBuffer();
byte[] encryptedBuffer = Crypto.Encrypt(byteArrayInput);
File.WriteAllBytes(fn, encryptedBuffer);
}
}
public static void OpenFile(string fn)
{
StoreMgr._doc = new Store();
using (MemoryStream ms = new MemoryStream(Crypto.Decrypt(File.ReadAllBytes(fn))))
{
DataContractSerializer deserializer = new DataContractSerializer(typeof(Store));
StoreMgr._doc = (Store)new DataContractSerializer(typeof(Store)).ReadObject(ms);
}
}
}
}
I've been stuck on this for quite some time. Any help is greatly appreciated!
If you configure System.Diagnostics.XmlWriterTraceListener in your web.config, you may find more helpful information in *.svclog
The issue was in the FileSaveAs method. byte[] byteArrayInput = ms.GetBuffer() was returning unused bytes. After switching it to byte[] byteArrayInput = ms.ToArray() program ran fine. Thanks for everyone's help.

Deserialize Dictionary with protobuf-net

Since the BinaryFormatter is giving me trouble serializing a Dictionary on Ios I decided to switch to protobuf-net. And use that to serialize stuff in my Unity3d game. Here is some code:
This is the class that hold all the data:
using System;
using System.Collections.Generic;
using ProtoBuf;
using UnityEngine;
namespace SerializationLib
{
[ProtoContract]
public class GameData
{
[ProtoMember(1)]
public int _coinAmount ;
[ProtoMember(2)]
public int _upgradeLevel;
[ProtoMember(3)]
public Level_Data[] _level_Data;
[ProtoMember(4)]
public CharacterUpgradeList _charUpgradeList;
[ProtoMember(5)]
public SerialVector2 serialVector;
}
[ProtoContract]
public class CharacterUpgradeList
{
private List<UpgradeData>[] upgData;
[ProtoMember(1,OverwriteList = true)]
public Dictionary<string, List<UpgradeData>> upgradeList;
public CharacterUpgradeList()
{
upgData = new List<UpgradeData>[4];
for (int i = 0; i < upgData.Length; i++)
{
upgData[i] = new List<UpgradeData> {
new UpgradeData(),
new UpgradeData(),
new UpgradeData(),
new UpgradeData(),
new UpgradeData(),
new UpgradeData()
};
}
upgradeList = new Dictionary<string, List<UpgradeData>>
{
{"Man",upgData[0]},
{"Woman",upgData[1]},
{"Boy",upgData[2]},
{"Girl",upgData[3]}
};
}
}
[ProtoContract]
public class Level_Data
{
[ProtoMember(1)]
public int completion_status;
[ProtoMember(2)]
public int star_Rating;
}
[ProtoContract]
public class UpgradeData
{
[ProtoMember(1)]
public bool lockStatus;
[ProtoMember(2)]
public bool purchased;
}
[ProtoContract]
public struct SerialVector2
{
[ProtoMember(1)]
public float x;
[ProtoMember(2)]
public float y;
public SerialVector2(Vector2 vect)
{
x = vect.x;
y = vect.y;
}
public Vector2 returnVector2()
{
return new Vector2(x, y);
}
}
}
This is the data serializer that I'm using
using System;
using System.Collections.Generic;
using SerializationLib;
using ProtoBuf.Meta;
namespace DataSerializer
{
class Program
{
static void Main(string[] args)
{
var Model = TypeModel.Create();
Model.Add(typeof(GameData), true);
Model.Add(typeof(CharacterUpgradeList), true);
Model.Add(typeof(Level_Data), true);
Model.Add(typeof(UpgradeData), true);
Model.Add(typeof(SerialVector2), true);
Model.AllowParseableTypes = true;
Model.AutoAddMissingTypes = true;
Model.Compile("DataSerializer", "DataSerializer.dll");
}
}
}
this is a protobuf wraper to use in my other c# scripts in unity
using UnityEngine;
using System.IO;
public static class ProtoWraper {
private static DataSerializer m_serialiezer = new DataSerializer();
public static T LoadObjectFromResources<T>(string resourcePath)
{
TextAsset objectAsset = Resources.Load(resourcePath, typeof(TextAsset)) as TextAsset;
if (objectAsset == null)
{
return default(T);
}
T deserializedObject = default(T);
using (MemoryStream m = new MemoryStream(objectAsset.bytes))
{
deserializedObject = (T)m_serialiezer.Deserialize(m, null, typeof(T));
}
return deserializedObject;
}
public static T LoadObjectFromPath<T>(string path)
{
if (!File.Exists(path))
{
return default(T);
}
T deserializedObject = default(T);
using(FileStream f = new FileStream(path,FileMode.Open))
{
deserializedObject = (T)m_serialiezer.Deserialize(f,null,typeof(T));
}
return deserializedObject;
}
public static void SaveObjectToPath<T>(string objectPath, string filename, T serializedObject)
{
if (!Directory.Exists(objectPath))
{
Directory.CreateDirectory(objectPath);
}
using (FileStream f = new FileStream(objectPath + filename, FileMode.OpenOrCreate))
{
m_serialiezer.Serialize(f, serializedObject);
}
}
}
now the problem is when I call data = ProtoWraper.LoadObjectFromPath<GameData>(filename); I get ArgumentException: An element with the same key already exists in the dictionary.
Nevermind, I was being a complete moron and not re-compiling the data serializer after changes to Serializationlib :D. It's all good now.

XML serialization C#, not processing certain fields

I have a serialization method as follows:
public string SerializeObject(object obj, Type type)
{
var setting = new XmlWriterSettings() { OmitXmlDeclaration = true, Indent = true };
var xml = new StringBuilder();
using (var writer = XmlWriter.Create(xml, setting))
{
var nsSerializer = new XmlSerializerNamespaces();
nsSerializer.Add(string.Empty, string.Empty);
var xmlSerializer = new XmlSerializer(type);
xmlSerializer.Serialize(writer, obj, nsSerializer);
}
return xml.ToString();
}
Which I call as follows:
requestXML = serializer.SerializeObject(InboundIterate, typeof(INBOUND));
The output is as expected for any field I have defined in my structure as a string, but all the decimal values are missing.
For example my output will look like:
<PRODUCT_EXTENSION>
<DIMENSION_UOM>IN</SD_DIMENSION_UOM>
<SALES_UOM>CS</SD_SALES_UOM>
</PRODUCT_EXTENSION>
when I am expecting
<PRODUCT_EXTENSION>
<DIMENSION_UOM>IN</DIMENSION_UOM>
<DIMENSION>15.83</DIMENSION>
<SALES_UOM>CS</SALES_UOM>
<SALES>24</SALES>
</PRODUCT_EXTENSION>
any help would be appreciated, thank you.
class below
public partial class PRODUCT_EXTENSION {
private System.Nullable<decimal> LENGTHField;
private bool LENGTHFieldSpecified;
private System.Nullable<decimal> NET_WEIGHTField;
private bool NET_WEIGHTFieldSpecified;
private string SALES_UOMField;
private string WEIGHT_UOMField;
private List<PRODUCT_EXTENSIONSOURCE_SYSTEM> SOURCE_SYSTEMField;
public PRODUCT_EXTENSION() {
this.SOURCE_SYSTEMField = new List<PRODUCT_EXTENSIONSOURCE_SYSTEM>();
}
public System.Nullable<decimal> LENGTH {
get {
return this.LENGTHField;
}
set {
this.LENGTHField = value;
}
}
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool SD_LENGTHSpecified {
get {
return this.LENGTHFieldSpecified;
}
set {
this.LENGTHFieldSpecified = value;
}
}
public System.Nullable<decimal> NET_WEIGHT {
get {
return this.NET_WEIGHTField;
}
set {
this.NET_WEIGHTField = value;
}
}
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool NET_WEIGHTSpecified {
get {
return this.NET_WEIGHTFieldSpecified;
}
set {
this.NET_WEIGHTFieldSpecified = value;
}
}
public string SALES_UOM {
get {
return this.SALES_UOMField;
}
set {
this.SALES_UOMField = value;
}
}
public string SD_WEIGHT_UOM {
get {
return this.WEIGHT_UOMField;
}
set {
this.WEIGHT_UOMField = value;
}
}
public List<PRODUCT_EXTENSIONSOURCE_SYSTEM> SOURCE_SYSTEM {
get {
return this.SOURCE_SYSTEMField;
}
set {
this.SOURCE_SYSTEMField = value;
}
}
}
I've tried your code snippet, and it works fine for me fine with public properties, but if i change the property protection to protected or private. These properties are missing from the XML.
Check your properties.

Using xml for a configuration file

I'm trying to figure out how to use XmlTextReader and XmlTextWriter for the configuration file of my program(s).
The xml file looks like this:
<?xml version="1.0" encoding="utf-8"?>
<Base>
<Global>
<some_config_value>86400</some_config_value>
<test1>t_1</test1>
<test2>t_2</test2>
<test3>t_3</test3>
<test4>t_4</test4>
</Global>
<test_head>
<test5>t_5</test5>
<test6>t_6</test6>
</test_head>
</Base>
And here is the class I have so far:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
namespace my_program.Global
{
class CXMLConfig
{
private string path;
public CXMLConfig(string filepath)
{
path = filepath;
}
public string XmlReadValue(string Section, string Key)
{
XmlTextReader textReader = new XmlTextReader(path);
ReadElements readEl = new ReadElements(textReader, Section, Key);
textReader.Close();
return readEl.Value;
}
private class ReadElements
{
XmlTextReader textReader;
string Section;
string Key;
private bool inBase = false;
private bool inSection = false;
private bool inKey = false;
public string Value { get; private set; }
public ReadElements(XmlTextReader textReader_set, string Section_set, string Key_set)
{
Value = "";
this.textReader = textReader_set;
this.Section = Section_set;
this.Key = Key_set;
textReader.Read();
while (textReader.Read())
{
// Move to fist element
textReader.MoveToElement();
string nodetype = textReader.NodeType.ToString();
if (textReader.LocalName == "Base")
{
if (nodetype == "Element")
{
if (!inBase)
inBase = true;
}
else if (nodetype == "EndElement")
{
if (inBase)
inBase = false;
}
}
else if (inBase && textReader.LocalName == Section)
{
if (nodetype == "Element")
{
if (!inSection)
inSection = true;
}
else if (nodetype == "EndElement")
{
if (inSection)
inSection = false;
}
}
else if (inBase && inSection && textReader.LocalName == Key)
{
if (inSection)
{
if (nodetype == "Element")
{
if (!inKey)
inKey = true;
}
else if (nodetype == "EndElement")
{
if (inKey)
inKey = false;
}
}
}
else if (inBase && inSection && inKey)
{
if (nodetype == "Text")
{
Value = textReader.Value.ToString();
//Console.WriteLine(Value);
}
}
}
}
}
}
}
So first of all, this is probably bad XML.. I have never used it before and it does look a little.. odd. And then there is the fact that I wrote this whole ReadElements class to read a value out of the config file, but I imagined there would be a much simpler way to do this with XmlTextReader (but I couldn't find it). And then lastly, I have yet to figure out how to update a value in the xml file using XmlTextWriter without re-writing the whole xml file from top to bottom.
You could use XmlSerializer to serialize and deserialize an arbitrary configuration class. Here is a sample implementation:
public enum MyEnum
{
ValueA,
ValueB
}
[Serializable]
public class Configuration : PersistableObject
{
public double A { get; set; }
public string B { get; set; }
public MyEnum C { get; set; }
}
public class PersistableObject
{
public static T Load<T>(string fileName) where T : PersistableObject, new()
{
T result = default(T);
using (FileStream stream = File.OpenRead(fileName))
{
result = new XmlSerializer(typeof(T)).Deserialize(stream) as T;
}
return result;
}
public void Save<T>(string fileName) where T : PersistableObject
{
using (FileStream stream = new FileStream(fileName, FileMode.CreateNew))
{
new XmlSerializer(typeof(T)).Serialize(stream, this);
}
}
}
For more information on how to configure XmlSerializer, have a look at the MSDN article: http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.aspx

Categories