MVC读取XML并使用ViewData显示
1.首先新建XMLFile1.xml 文件,放在App_Data 文件夹下面。
<?xml version="1.0" encoding="utf-8" ?> <A> <B> <C> <SuccessfulValidations> <SuccessfulValidationResult> <ProductKeyID>111</ProductKeyID> <HardwareHash>fasfadsqwerafa</HardwareHash> </SuccessfulValidationResult> <SuccessfulValidationResult> <ProductKeyID>222</ProductKeyID> <HardwareHash>efmfsfmfioefm</HardwareHash> </SuccessfulValidationResult> <SuccessfulValidationResult> <ProductKeyID>333</ProductKeyID> <HardwareHash>rerererrqrwe</HardwareHash> </SuccessfulValidationResult> </SuccessfulValidations> </C> </B> </A>
2.在controller里面新建一个SuccessfulValidationResult类
public class SuccessfulValidationResult { public string ProductKeyID { get; set; } public string HardwareHash { get; set; } }
3. 读取xml数据保存到ViewData中
public ActionResult ScannedDigitaldocumentList() { XDocument xdoc = XDocument.Load(HttpContext.Server.MapPath("~/App_Data/XMLFile1.xml")); IEnumerable<XElement> xex = xdoc.Element("A") .Element("B") .Element("C") .Element("SuccessfulValidations") .Elements("SuccessfulValidationResult"); List<SuccessfulValidationResult> listData = new List<SuccessfulValidationResult>(); foreach (XElement item in xex) { SuccessfulValidationResult sfvr= new SuccessfulValidationResult(); sfvr.ProductKeyID = item.Element("ProductKeyID").Value.Trim(); sfvr.HardwareHash = item.Element("HardwareHash").Value.Trim(); listData.Add(sfvr); } ViewData["xml"] = listData; return View(); }
4.在前台显示:
<div id="ljj"> @{ foreach (var item in (List<SIL.AARTO.Web.Controllers.ScannedDigitaldocument.SuccessfulValidationResult>)ViewData["xml"]) { @item.ProductKeyID<br /> @item.HardwareHash } } </div>
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。