漫话Linq——Linq To XML
Linq TO XML技术交流学习案例:
#region 全局变量
/// <summary>
/// XML path
/// </summary>
public String x_Path = String.Empty;
/// <summary>
/// 查询关键字 x_Name
/// </summary>
public String key = String.Empty;
/// <summary>
/// DataSet ds
/// </summary>
public DataSet ds = new DataSet();
/// <summary>
/// x_Id
/// </summary>
public static String x_Id = String.Empty;
#endregion
#region 读取数据
/// <summary>
/// 加载数据 one
/// </summary>
public void LoadXML_One()
{
/*
* 此种方式绑定到 GridView 不能支持 GridView自带的分页功能,
* 并且还不稳定,容易出错(不推荐)
*/
//加载 XML
XElement elements = XElement.Load(x_Path);
try
{
var query = from xm in elements.Elements("ChildNodes")
orderby xm.Element("x_Age").Value descending
select new //注意前面绑定什么字段(DataField),这里就查询什么字段
{
x_Id = xm.Attribute("x_Id").Value.Trim(), //x_Id 是属性 使用 Attribute获取
x_Name = xm.Element("x_Name").Value.Trim(),
x_Gender = xm.Element("x_Gender").Value.Trim(),
x_Age = xm.Element("x_Age").Value.Trim(),
x_Address = xm.Element("x_Address").Value.Trim(),
x_Tel = xm.Element("x_Tel").Value.Trim(),
x_Remark = xm.Element("x_Remark").Value.Trim()
};
this.gvXML.DataSource = query;
this.gvXML.DataBind();
}
catch (Exception ex)
{
ClientScript.RegisterStartupScript(GetType(), "", "alert('系统异常!具体如下:" + ex.Message.ToString() + "');", true);
}
}
/// <summary>
/// 加载数据 Two
/// </summary>
public void LoadXML_Two()
{
/*
* 方法二比较方法一更稳定,不过有些复杂,
* 主要是借助 Linq To DataSet的一些技术(这节知识在后面介绍),
* 别且此种方法可以支持 GridView自带分页功能(推荐)
*/
try
{
//加载XML文件到 ds中
ds.ReadXml(x_Path);
if (ds != null && ds.Tables.Count > 0)
{
IEnumerable<DataRow> query = from xm in ds.Tables[0].AsEnumerable()
orderby xm.Field<String>("x_Age") descending
select xm;
this.gvXML.DataSource = query.CopyToDataTable();
this.gvXML.DataBind();
}
}
catch (Exception ex)
{
ClientScript.RegisterStartupScript(GetType(), "", "alert('系统异常!具体如下:" + ex.Message.ToString() + "');", true);
}
}
#endregion
/// <summary>
/// 查询方式一
/// </summary>
public void SearchXML_One()
{
XElement elements = XElement.Load(x_Path);
var query = from xm in elements.Elements("ChildNodes")
where xm.Element("x_Name").Value.Contains(key)
orderby xm.Element("x_Age") descending
select new
{
x_Id = xm.Attribute("x_Id").Value.Trim(), //x_Id 是属性 使用 Attribute获取
x_Name = xm.Element("x_Name").Value.Trim(),
x_Gender = xm.Element("x_Gender").Value.Trim(),
x_Age = xm.Element("x_Age").Value.Trim(),
x_Address = xm.Element("x_Address").Value.Trim(),
x_Tel = xm.Element("x_Tel").Value.Trim(),
x_Remark = xm.Element("x_Remark").Value.Trim()
};
if (query != null)
{
this.gvXML.DataSource = query;
this.gvXML.DataBind();
}
}
/// <summary>
/// 查询方式二
/// </summary>
public void SearchXML_Two()
{
/*
* 此种查询方式较第一种更稳定,压力也会更大
*/
ds = new DataSet();
ds.ReadXml(x_Path);
if (ds != null && ds.Tables.Count > 0)
{
IEnumerable<DataRow> query = from xm in ds.Tables[0].AsEnumerable()
where xm.Field<String>("x_Name").Contains(key)
orderby xm.Field<String>("x_Age") descending
select xm;
if (query != null)
{
if (query.Count() > 0)
{
this.gvXML.DataSource = query.CopyToDataTable();
this.gvXML.DataBind();
}
else
{
ClientScript.RegisterStartupScript(GetType(), "", "alert('查询的信息不存在');", true);
}
}
}
}
/// <summary>
/// 提交信息
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (!IsEmpty())
{
try
{
XElement elements = XElement.Load(x_Path);
if (String.IsNullOrEmpty(x_Id)) //新增
{
XElement new_Child = new XElement("ChildNodes",
new XAttribute("x_Id", Guid.NewGuid()),
new XElement("x_Name", this.tbox_Name.Text.Trim()),
new XElement("x_Gender", this.tbox_Gender.Text.Trim()),
new XElement("x_Age", this.tbox_Age.Text.Trim()),
new XElement("x_Address", this.tbox_Address.Text.Trim()),
new XElement("x_Tel", this.tbox_Tel.Text.Trim()),
new XElement("x_Remark", this.tbox_Remark.Text.Trim())
);
elements.Add(new_Child);
elements.Save(x_Path);
}
else
{
//修改
IEnumerable<XElement> element = from xm in elements.Elements("ChildNodes")
where xm.Attribute("x_Id").Value.Equals(x_Id)
select xm;
if (element != null && element.Count() > 0)
{
XElement first = element.First();
first.SetElementValue("x_Name", this.tbox_Name.Text.Trim());
first.SetElementValue("x_Gender", this.tbox_Gender.Text.Trim());
first.SetElementValue("x_Age", this.tbox_Age.Text.Trim());
first.SetElementValue("x_Address", this.tbox_Address.Text.Trim());
first.SetElementValue("x_Tel", this.tbox_Tel.Text.Trim());
first.SetElementValue("x_Remark", this.tbox_Remark.Text.Trim());
elements.Save(x_Path);
}
}
ClientScript.RegisterStartupScript(GetType(), "", "alert('" + (String.IsNullOrEmpty(x_Id) == true ? "添加" : "修改") + "成功!');", true);
LoadXML_Two();
//隐藏
this.dt_Add.Attributes.Add("style", "display: none;");
//清空
Clearn();
}
catch (Exception ex)
{
ClientScript.RegisterStartupScript(GetType(), "", "alert('系统异常!具体如下:" + ex.Message.ToString() + "');", true);
}
}
else
{
ClientScript.RegisterStartupScript(GetType(), "", "alert('输入不为空!');", true);
this.dt_Add.Attributes.Remove("style");
}
}
/// <summary>
/// 删除信息
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void gvXML_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
String x_Id = this.gvXML.DataKeys[e.RowIndex].Value.ToString().Trim();
if (!String.IsNullOrEmpty(x_Id))
{
XElement elements = XElement.Load(x_Path);
IEnumerable<XElement> element = from xm in elements.Elements("ChildNodes")
where xm.Attribute("x_Id").Value.Trim().Equals(x_Id)
select xm;
if (element.Count() > 0)
{
//删除
element.First().Remove();
elements.Save(x_Path);
//重新加载
LoadXML_Two();
ClientScript.RegisterStartupScript(GetType(), "", "alert('删除成功成功!');", true);
}
}
}
扩充:
#region DataSet、查询结果 转化为XML
/// <summary>
/// 转化为XML
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void ButnGetXML_Click(object sender, EventArgs e)
{
XDocument xdm = new XDocument(
new XDeclaration("1.0", "utf-8", "yes"),
new XComment("这里声明相关属性"),
new XElement("RootNode",
new XComment("这是一个父节点"),
from es in dc.EA_Script
where es.Id <= 150
select new XElement[]{
new XElement("ChildNodes",
new XComment("这里是子节点"),
new XAttribute("x_Id",es.Id),
new XElement("x_Title",es.Title),
new XElement("x_Url",es.FName),
new XElement("x_Detail",es.Detail),
new XElement("x_Downloads",es.Downloads),
new XElement("x_DateTime",es.DateTime.ToString())
)}
)
);
xdm.Save(x_Path);
ClientScript.RegisterStartupScript(GetType(), "", "alert('创建XML文件成功!')", true);
}
/// <summary>
/// DataSet数据转化为XML文件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void btnDSGetXML_Click(object sender, EventArgs e)
{
StringBuilder strSQL = new StringBuilder();
strSQL.Append("SELECT TOP(88) * FROM [dbo].EA_Script es ORDER BY es.Id DESC");
con = new SqlConnection(ConnectionString);
sda = new SqlDataAdapter(strSQL.ToString(), con);
try
{
DataSet ds = new DataSet();
sda.Fill(ds, "DSGetXML");
ds.WriteXml(x_Path);
}
catch (Exception ex)
{
ClientScript.RegisterStartupScript(GetType(), "", "alert('DataSet创建DataSetXML文件失败!\n" + ex.Message + "')", true);
}
finally
{
sda.Dispose();
ds.Dispose();
if (con.State == ConnectionState.Open) con.Close();
}
ClientScript.RegisterStartupScript(GetType(), "", "alert('DataSet创建DataSetXML文件成功!')", true);
}
#endregion