XmlSerializer and defaults

D

dmonder

I am using the XMLSerializer to map the XML below to an object as
follows:

Config config
XmlSerializer xmls = new XmlSerializer( typeof( Config ) );
try {
TextReader tr = new StreamReader( "config.xml" );
config = (Config)xmls.Deserialize( tr );
tr.Close();
} catch (System.IO.FileNotFoundException) {
// How do I set up the defaults??
}

My problem is that I want to be able set my config object to defaults
if the xml file is not found. Any ideas?

David

----- XML File -----

<?xml version="1.0"?>
<Config>
<Directories>
<Directory Name="Cleaned" Location="" />
<Directory Name="Received" Location="" />
</Directories>
<Extention Default="csv" />
<Files>
<File Name="Cleaned" Location="" />
<File Name="Received" Location="" />
</Files>
<FileHistory>
<FileName></FileName>
</FileHistory>
<Filters Sorted="true">
<Filter>
<Name>All files (*.*)</Name>
<Data>*.*</Data>
</Filter>
<Filter>
<Name>Comma Separated Files (*.csv)</Name>
<Data>*.csv</Data>
<Selected/>
</Filter>
</Filters>
</Config>
 
J

John Saunders [MVP]

My answers are inline:
I am using the XMLSerializer to map the XML below to an object as
follows:

Config config
XmlSerializer xmls = new XmlSerializer( typeof( Config ) );
try {
using(TextReader tr = new StreamReader( "config.xml" ))
{
config = (Config)xmls.Deserialize( tr ); }
} catch (System.IO.FileNotFoundException) {
// How do I set up the defaults??
config = new Config();
config.Property1 = defaultForProperty1;
// etc.
 
A

Alex Meleta

} catch (System.IO.FileNotFoundException) {
// How do I set up the defaults??

For example :
You can read from default xml from resources.
or
You can directly set the default values
config = new Config();
confic.variables = defaultValue;
}
or define Config with pre-set default values.

Alex
http://devkids.blogspot.com
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top