In many of my projects ,I used this approach where I need to populate my drop down list with all the countries and based on the selected country, I need to populate my State dropdown list.The main problem I faced then was data for all countries and states.After looking on various services and databases available on internet,I found this approach best suitable and easy.Here I will read xml file and populate my Lists with countries and states.Here I have mapped the path of file using Server.Mappath and then read the file node by node using XmlReader.I have used switch case for different types of node like country ,state.And then populate my Lists at their respective positions in the code.Finally I have passed on these list to my service call to save them into country and state table.
Here Country tables has two columns CountryId(auto-generated ,PK) and country name and state table has stateId(auto-generated,pk), state name,country Id. Below is the code
List<StateData> list= new List<StateData>();
List<string> countryList= new List<string>();
string countryName = string.Empty;
int countryId = 0;
var path = Server.MapPath("~/country_state.xml");
using (System.Xml.XmlReader reader = System.Xml.XmlReader.Create(path))
{
while (reader.Read())
{
// Only detect start elements. if (reader.IsStartElement())
{
// Get element name and switch on it. switch (reader.Name)
{
case "countries":
// Detect this element. Console.WriteLine(reader.Name);
break;
case "country":
// Detect this article element. Console.WriteLine("country");
// Search for the attribute name on this current node. string attribute = reader["name"];
if (attribute != null)
{
countryName = attribute;
countryList.Add(countryName);
countryId++;
Console.WriteLine(" Has attribute name: " + attribute);
}
break;
case "state":
Console.WriteLine("state");
if (reader.Read())
{
Console.WriteLine(" State Name " + reader.Value.Trim());
Console.WriteLine(" Country Name " + countryName + ", Id = " + countryId);
list.Add(new StateData { CountryId = countryId, StateName = reader.Value.Trim() });
}
break;
}
}
}
}
// Calling Service Methods Here Services.RMService cl= new RMService();
cl.SaveCountriesInTable(countryList);
cl.SaveStateData(list);
Console.ReadLine();
}
Attached below is the code and xml file
ReadXML.zip (30.29 kb)
e48ea63a-56b4-4c20-b3ce-a40b0b7c2bf4|0|.0
Categories:
30. January 2012
Tags:
Read XML, Country-State Db