0
我正在尝试使用XML文件中的数据填充我的模型,但到目前为止尚未成功。在变量Res中设置断点显示空值。在ASP.NET中绑定来自XML的数据问题
我也试过在本地加载XML文件,但结果是一样的。
我正在使用VS2013,MVC。
控制器:
public ActionResult Index()
{
IQueryable<Restaurant> Res;
XDocument xmlDoc = XDocument.Load
("http://ratings.food.gov.uk/OpenDataFiles%5CFHRS501en-GB.xml");
var model =
from xml in xmlDoc.Descendants("EstablishmentDetail")
select new Restaurant
{
FHRSID = (int)xml.Element("FHRSID"),
BusinessName = (string)xml.Element("BusinessName"),
RatingValue = (int)xml.Element("RatingValue"),
HygieneScore = (int)xml.Element("Hygiene"),
};
Res = model.AsQueryable();
return View(Res);
}
型号:
<FHRSEstablishment>
<Header>
<ExtractDate>2014-09-19</ExtractDate>
<ItemCount>933</ItemCount>
<ReturnCode>Success</ReturnCode>
</Header>
<EstablishmentCollection>
<EstablishmentDetail>
<FHRSID>129104</FHRSID>
<LocalAuthorityBusinessID>5952</LocalAuthorityBusinessID>
<BusinessName>5 Elm's Cafe</BusinessName>
<RatingValue>3</RatingValue>
<Scores>
<Hygiene>10</Hygiene>
<Structural>10</Structural>
<ConfidenceInManagement>10</ConfidenceInManagement>
</Scores>
</EstablishmentDetail>
</EstablishmentCollection>
</FHRSEstablishment>
我很新的一般的Web开发,这是我第一次:从XML文件
[XmlRoot("EstablishmentDetails")]
public class Restaurant
{
public int? RestaurantId { get; set; }
[XmlElement("FHRSID")]
public int FHRSID { get; set; }
[XmlElement("BusinessName")]
public string BusinessName { get; set; }
[XmlElement("RatingValue")]
public int? RatingValue { get; set; }
[XmlElement("Hygiene")]
public int? HygieneScore { get; set; }
}
样品使用XML文件。
新控制器:
public class RestaurantController : Controller
{
public static IEnumerable<Restaurant> GetData()
{
XDocument xmlDoc = XDocument.Load(@"~/Xml/OpenDataFiles_FHRS501en-GB.xml");
foreach (var xml in xmlDoc.Descendants("EstablishmentDetail"))
{
var eFHRSID = xml.Element("FHRSID");
var eBusinessName = xml.Element("BusinessName");
var eRatingValue = xml.Element("RatingValue");
var eHygieneScore = xml.Element("Scores").Element("Hygiene");
if (eFHRSID != null && eBusinessName != null && eRatingValue != null && eHygieneScore != null)
{
yield return new Restaurant
{
FHRSID = (int)eFHRSID,
BusinessName = (string)eBusinessName,
RatingValue = (int)eRatingValue,
HygieneScore = (int)eHygieneScore,
};
}
}
}
public ActionResult Index()
{
GetData();
return View();
}
感谢你的意见,嵌套在你的代码示例是有道理的。也许正如所料,我现在正在得到一个空错误,特别是“对象引用未设置为对象的实例”。我已经尝试了一些东西,例如在模型中将属性设置为空,并且在从XML文档分配值之前实例化变量并分配一些值。但似乎没有清理空错误。如果有帮助,我已将最新的控制器添加到原始问题中。 – user3626232 2014-10-29 15:45:30
您必须能够精确定位为空的确切行/成员。使用调用堆栈,堆栈跟踪等...我看到您在此期间编辑了您的帖子。您的模型具有xml序列化属性。你从LinqToXml移动到自定义反序列化?您的源XML已成功解析与答案中的代码。 – 2014-10-30 04:16:48