I am trying to query a public web service that returns the following xml:
This XML file does not appear to have any style information associated with it. The document tree is shown below.
<string xmlns="http://www.webserviceX.NET">
<NewDataSet> <Table> <Country>Maldives</Country> <City>Gan</City> </Table> <Table> <Country>Maldives</Country> <City>Male</City> </Table> </NewDataSet>
</string>
How can I get the list of cities in c# for loading a dropdowlist?
This is my code:
var restClient = new RestClient("http://www.webservicex.net/globalweather.asmx/GetCitiesByCountry");
var request = new RestRequest(Method.GET);
// request.Resource = "{version}/token";
request.AddParameter("CountryName", "Maldives");
var response = restClient.Execute(request);
//response.Content contains the troublesome string
I would appreciate your help, thanks.
Looks like your XML consists of the output of DataSet.WriteXml(writer, XmlWriteMode.IgnoreSchema)
wrapped in a root element named "{http://www.webserviceX.NET}string"
. So it will be easiest to deserialize the inner XML as a DataSet
then bind the appropriate column of the appropriate DataTable
:
First, deserialize the set:
var rootElement = XElement.Parse(xmlString); // xmlString is //response.Content
var set = new DataSet();
var setElement = rootElement.DescendantsAndSelf().Where(e => e.Name.LocalName == "NewDataSet").FirstOrDefault();
if (setElement != null)
{
using (var reader = setElement.CreateReader())
{
set.ReadXml(reader, XmlReadMode.Auto);
}
}
Next, pick out a table with a column named "City"
:
var table = set.Tables.Cast<DataTable>().FirstOrDefault(t => t.Columns["City"] != null);
Now that you have a DataTable
, you can bind it following the instructions in What is the right way to populate a DropDownList from a database? , DropdownList DataSource and/or Databind a dropdownlist using DataTextField = "City"
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.