Reputation: 189
I've got an app with config.xml file added for user settings.
I am reading it simply by:
DataSet config = new DataSet();
config.ReadXml(configPath);
Parameters in config.xml are in columns grouped under some tables:
<?xml version="1.0" standalone="yes"?>
<UserSetup>
<TableA>
<revBegin>value1</revBegin>
<revEnd>value2</revEnd>
...
</TableA>
...
</UserSetup>
What I'm looking for is a clean way to read from DataSet config, without memorizing table or column names.
In my current implementation I achieved that by following class:
public static class MyTables
{
public static class TableA
{
public const String name = "TableA";
public const String revBegin = "revBegin";
public const String revEnd = "revEnd";
...
}
...
}
And I read values like this:
String revEnd = config.Tables[MyTables.TableA.name].Rows[0][MyTables.TableA.revEnd].ToString();
But I somehow fill that it is quite easy problem solved in quite complicated - not to say nasty - way.
Do you have any idea how can I make things simpler or cleaner?
P.S. At some point I tried reducing config.Tables[MyTables.TableA.name]
part to config.Tables[MyTables.TableA]
but - how I see it - it would require adding Index[object]
to sealed class DataTableCollection
and overriding ToString()
method in my static class - both impossible. Am I right?
Upvotes: 0
Views: 165
Reputation: 2890
Unless you absolutely have to use a DataSet to read the XML, you can achieve the same results using XML serialization. Annotate your classes with the below.
[XmlRoot]
[Serializable]
public class UserSetUp
{
[XmlElement]
public TableA TableA { get; set; }
}
[Serializable]
public class TableA
{
[XmlElement]
public string revBegin { get; set; }
[XmlElement]
public string revEnd { get; set; }
}
Assuming your config in on C:\ for this example.
var configStream = File.OpenRead(@"C:\Config.xml");
var reader = new StreamReader(configStream);
var xmlString = reader.ReadToEnd();
var serializer = new XmlSerializer(typeof(UserSetUp));
var stringReader = new StringReader(xmlString);
var userSetup = (UserSetUp)serializer.Deserialize(stringReader);
I've tested it with the below XML and it works ok.
<?xml version="1.0" encoding="utf-16" ?>
<UserSetUp>
<TableA>
<revBegin>1</revBegin>
<revEnd>2</revEnd>
</TableA>
</UserSetUp>
Hope that helps you on your way.
Upvotes: 1