转载自 http://www.wyjexplorer.cn/Blog/View/A723254D5450AC35.html
前天嘴贱,建议老Y用XML存一个表格然后绑给GridView,本意是用个偷懒的办法快速解决了那个case,结果做的时候没那么方便,或者说直接把GridView绑定到一个XML文件不太好,如果通过DataTable来处理也显得比较麻烦。
比较好的办法其实是绑给业务对象,就和以前ORM一样做,GridView最终绑的是一个List<数据Model>。那么怎么来读取XML呢最方便呢?当然是用LINQ!可以参考我博客上的这篇文章:http://www.wyjexplorer.cn/Blog/View/EC3073A1BDFB9D90.html
今天抽出来单独写了一个Demo示众,3步搞定!
1.搞个XML文件:
<?xml version="1.0" encoding="utf-8" ?>
<Contacts>
<Person>
<Id>1</Id>
<Name>Fucker</Name>
<Mobile>13838389438</Mobile>
<Address>No.250, Fucking Road</Address>
</Person>
<Person>
<Id>2</Id>
<Name>Dick</Name>
<Mobile>1234567890123</Mobile>
<Address>No.13, 2B Road, Shit City</Address>
</Person>
<Person>
<Id>3</Id>
<Name>Shitter</Name>
<Mobile>987654321098</Mobile>
<Address>No.38, SB Street</Address>
</Person>
</Contacts>
2.给他创建一个数据模型类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
/// <summary>
/// Summary description for Person
/// </summary>
namespace LinqXMLGridViewDemo
{
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public string Mobile { get; set; }
public string Address { get; set; }
public Person()
{
//
// TODO: Add constructor logic here
//
}
}
}
3. 页面上拖个GridView,后台代码这样写:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using LinqXMLGridViewDemo;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
var query = GetXMLData();
gvContact.DataSource = query;
gvContact.DataBind();
}
private List<Person> GetXMLData()
{
var xDoc = XDocument.Load(Server.MapPath("~/App_Data/Data.xml"));
var query = (from person in xDoc.Descendants("Person")
select new Person()
{
Id = Convert.ToInt32(person.Element("Id").Value),
Name = person.Element("Name").Value,
Mobile = person.Element("Mobile").Value,
Address = person.Element("Address").Value
}).ToList();
return query;
}
}
有图有真相:
碉堡了~