2011-07-31 75 views
0

我有一個xml below.now我想根據選定的狀態填充下拉列表中的所有城市(代碼如下),但我只得到第一個城市,而不是所有城市。 如何獲取所有城市。請參閱下面的代碼。如何填充城市對應的選定狀態

<?xml version="1.0" encoding="utf-8" ?> 
<states> 
    <state> 
    <stateid>1</stateid> 
    <city>umr</city> 
    <city>kat</city> 
    <city>jpl</city> 
    <city>bpl</city> 
    </state> 
    <state> 
    <stateid>2</stateid> 
    <city>mumbai</city> 
    <city>dadar</city> 
    <city>ghat</city> 
    <city>kanjur</city> 
    </state> 
</states> 

這裏1是stateid,在狀態中有像umr.kat,jpl bpl這樣的城市。

public static List<statecs> GetStateFromXML(string getstateid) 
{ 
    XDocument xmlDoc = XDocument.Load(
      HttpContext.Current.Server.MapPath("stateXML.xml")); 
    var states = from state in xmlDoc.Descendants("state") 
       where state.Element("stateid").Value == getstateid 
       select new statecs { City = state.Element("city").Value, }; 
    return states.ToList(); 
} 
+0

爲什麼不把'stateid'作爲'state'屬性? –

回答

0

這可能工作...不是測試或編譯

// fetch states first 
    var states = from state in xmlDoc.Descendants("state") 
     where state.Element("stateid").Value == getstateid 
     select state; 

    // for found states select the city. 
    var cities = from city in states.Descendants("city") 
        select new statecs { City = city.Value, };  

    return cities.ToList(); 
+0

thanksssssssss its workingggggg – jenifer

0

可以使用的SelectMany:

return xmlDoc.Descendants("state") 
    .Where(state => state.Element("stateid").Value == getstateid) 
    .SelectMany(state => state.Elements("city").Select(city => new statecs { City = city.Value })) 
    .ToList(); 
相關問題