0

我将 XML 内容绑定到 MVC4 中的下拉列表。从链接中,我尝试读取 XML 文件的内容。代码中的 Where 子句返回 Object 不引用到对象的实例。如果没有 where 条件,则从文件中读取 xml 内容。我只想显示基于大写字母 ID=1 的值。
XML

<?xml version="1.0" encoding="utf-8"?>
<State>
<Capital ID="1" CountryName="India">
    <city name="Andaman and Nicobar Islands" value="AN"></city>
    <city name="Andhra Pradesh" value="AP"></city>
</Capital>  
<Capital ID="2" CountryName="USA">
    <city name="Alabama" value="AL"></city>
    <city name="Alaska" value="AK"></city>
</Capital>  
</State>

控制器

 public ActionResult Details()
{
 string UserID = 12345;
 string partnerid = XCWERT;
 var file = Path.Combine(Server.MapPath("~/App_Data"), "States.xml");            
 var model = new CheckoutModel
 {    
  States =
  from unit in XDocument.Load(file).Document.Elements("State").Elements("Capital").Elements("city") -- This loads all the values
  //   from unit in XDocument.Load(file).Document.Descendants("Capital").Where(unit => (string)unit.Attribute("ID").Value == "1") -- where condition is not accepting and throwing error
   select new SelectListItem
  {
    Text = unit.Attribute("name").Value,
    Value = unit.Attribute("value").Value,                      
  }                     
};
 SelectList selectList = new SelectList(model.States, "Value", "Text");
 ViewData["StateOptions"] = selectList;          
 return View(GetShippingAddress(UserID, partnerid));
 }

看法

 @Html.DropDownList("State", ViewData["StateOptions"] as IEnumerable<SelectListItem>, "(Select one)", new { @class = "TextBoxBorder" })

我的代码中有什么错误。? 任何建议都会有很大帮助

4

1 回答 1

2

它应该是这样的

var result = XDocument.Load(fileName)
                .Descendants("Capital")
                .First(c => (string)c.Attribute("ID") == "1")
                .Descendants("city")
                .Select(c => new
                {
                    Text = (string)c.Attribute("name"),
                    Value = (string)c.Attribute("value"),
                })
                .ToList();
于 2013-05-22T07:37:38.250 回答