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>