Linq读xml

读取 XML最方便的当然是用LINQ!可以参考博客上的这篇文章:http://www.wyjexplorer.cn/Blog/View /EC3073A1BDFB9D90.html

Demo

1.搞个XML文件:

<?xml version="1.0" encoding="utf-8" ?>
<Contacts>
<Person>
<Id>1</Id>
<Name>**er</Name>
<Mobile>13838389438</Mobile>
<Address>No.250, **ing Road</Address>
</Person>
<Person>
<Id>2</Id>
<Name>Dick</Name>
<Mobile>1234567890123</Mobile>
<Address>No.13, 2B Road, ** City</Address>
</Person>
<Person>
<Id>3</Id>
<Name>**ter</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;
}

}

有图有真相: 

 

posted on 2012-11-12 17:38  快乐牛牛之家  阅读(174)  评论(0)    收藏  举报

导航