1

I have a namespace Common.Param in which i created a bunch of simple classes of static strings like this:

public class Url
{
    public static string LoginPage;
    public static string AdminPage;
    public static string ProfilePage;
}

public class LoginDetails
{
    public static string Username;
    public static string Password;
}

I want to fill those fields with a xml file made like this

<Param>
  <Url>
    <LoginPage>http://1.2.3.4/Login.aspx</LoginPage>
    <AdminPage>http://1.2.3.4/Admin.aspx</AdminPage>
    <ProfilePage>http://1.2.3.4/Profile.aspx</ProfilePage>
  </Url>
  <LoginDetails>
    <Username>myUser</Username>
    <Password>p4ssw0rd</Password>
  </LoginDetails>
...
</Param>

How can i find all classes within my Common.Param namespace and fill their strings programmatically?

Doc
  • 5,078
  • 6
  • 52
  • 88
  • 1
    Better create a static class that holds a class without static properties and fill/create that class from the XML. You will be able to use almost any XML parser library out there. – Tarion Feb 21 '14 at 13:47
  • can you explain, please? i didn't understand what you mean... – Doc Feb 21 '14 at 13:56

2 Answers2

4

Of course you can do it:

var xdoc = XDocument.Load(path_to_xml);
var url = xdoc.Root.Element("Url");
Url.LoginPage = (string)url.Element("LoginPage");
Url.AdminPage = (string)url.Element("AdminPage");
Url.ProfilePage = (string)url.Element("ProfilePage");
var login = xdoc.Root.Element("LoginDetails");
LoginDetails.Username = (string)login.Element("Username");
LoginDetails.Password = (string)login.Element("Password");

But as @Tarion correctly pointed, I would go with non-static data instead. Static data introduce coupling to your system. Also you will not be able to use xml serialization with static data.

Thus your element names in xml match members of your classes, then deserialization will be really simple. Just create Param class which holds both Url and LoginDetails:

public class Param
{
    public Url Url { get; set; }
    public LoginDetails LoginDetails { get; set; }
}

public class Url
{
    public string LoginPage { get; set; }
    public string AdminPage { get; set; }
    public string ProfilePage { get; set; }
}

public class LoginDetails
{
    public string Username { get; set; }
    public string Password { get; set; }
}

Deserialization:

XmlSerializer serializer = new XmlSerializer(typeof(Param));
using(StreamReader reader = new StreamReader(path_to_xml))
{
     Param param = (Param)serializer.Deserialize(reader);
}
Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
1

The general thing you are looking for is "Serialization" / "Deserialization".

There are lots of very competent libraries for this. Try looking here

Community
  • 1
  • 1
Iain Ballard
  • 4,433
  • 34
  • 39