Home
C# XML To Class/Object Basics
We have an XML file thus...
<?xml version="1.0" encoding="utf-8" ?>
<Settings>
<UseThisServer>
mail.myserver.com
</UseThisServer>
<UseThisEmailAddress>
john.doe@gmail.com
</UseThisEmailAddress>
<UseThisPassword>
#ComplexPass~)(*)
</UseThisPassword>
</Settings>
First off - the namespace
using System.Xml.Serialization;
We want to get this information into a nice class or object so we can use it in our code. So here is our class
public class Settings
{
public bool UseThisServer{ get; set; }
public string UseThisEmailAddress { get; set; }
public int UseThisPassword { get; set; }
}
Now our actual code
Settings MySettings = new Settings();
XmlSerializer MySerial = new XmlSerializer(typeof(Settings));
using (Stream MyReader = new FileStream("c:\\myfolder\\myfile.xml", FileMode.Open))
{
MySettings = (Settings)MySerial.Deserialize(MyReader);
}
MySettings.EmailServer = MySettings.EmailServer.Trim();
MySettings.Username = MySettings.Username.Trim();
MySettings.Password = MySettings.Password.Trim();
What's happening?
Create MySettings as an instance of settings ready to be populated
Create an XMLSerializer with a typeof of the class we're trying to populate
Using a streamreder we open the file that is the XML file
MySettings which is a Settings class has the filestream pushed through it using the format of Settings...
Reader's Comments
Name
Comment
Add a RELEVANT link (not required)
Upload an image (not required)
Uploading...
Home