Populating Values Into A Class From An XML,



I have a XML with me as shown below



<Country>
<Name>Countryname</Name>
<Continent>ContinentName</Continent>
<Zone>TimeZone</Zone>
<India>
<State>
<StateName>nameoftheState</StateName>
<StateCode>codeofthestate</StateCode>
</State>
</India>
</Country>


This XML has to be populated into a class whose structure is as given below



public class Country
{
public string Name { get; set; }
public string Continent { get; set; }
public string Zone { get; set; }
public India IndiaInfo { get; set; }

}

public class India
{
public List<State> StateInfo{get; set;}
}

public class State
{
public string StateName { get; set; }
public string StateCode { get; set; }
}


DeSerializng the XML to an object is not an option as this XML will pass through another layer which will parse the XML and take out individual elements needed the fill the class.I have written the code to take those values and fill the object as shown below



public void PopulateCountry(string name, string Asia , string GMT , string AbcState, string RichState)
{
Country objCountry = new Country();
objCountry.Continent = Asia;
objCountry.Name = name;
objCountry.Zone = GMT;

**India objIndia = new India();
objIndia.StateInfo = new List<State>;
State objState = new State();
objState.StateCode = AbcState;
objState.StateName = RichState;
objIndia.StateInfo.Add(objState);
objCountry.IndiaInfo = objIndia;**



}


In the above method to populate the object of class Country i have taken a brute force approach and put the values in the class and the code is giving results too . However this code is not following some of the best practices and can be further enhanced /rewritten especially the one in Bold. Can someone point out the things/features/practices of C# i am missing .


No comments:

Post a Comment