如何填充城市对应的选定状态

时间:2011-07-31 15:42:33

标签: linq

我有一个下面的xml。现在我想根据选定的状态填写下拉列表中的所有城市(代码如下),但我只获得第一个城市而不是所有城市。 如何获得所有城市。请参阅下面的代码。

<?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(); 
}

2 个答案:

答案 0 :(得分: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();

答案 1 :(得分: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();
相关问题