标签:style blog http color 使用 io strong 文件
protected void btnGenerateXml_Click(object sender, EventArgs e) { if (File.Exists(Server.MapPath("~/xml/stus.xml"))) { ClientScript.RegisterStartupScript(this.GetType(),"","alert(‘xml文件已经存在!‘)",true); return; } var xDoc = new XDocument(new XElement("students", new XElement("student", new XElement("name", "张三"), new XElement("age", 23), new XAttribute("num", "S001")), new XElement("student", new XElement("name", "李四"), new XElement("age", 24), new XAttribute("num", "S002")), new XElement("student", new XElement("name", "王五"), new XElement("age", 25), new XAttribute("num", "S003")))); //xDoc输出xml的encoding是系统默认编码,对于简体中文操作系统是gb2312 //默认是缩进格式化的xml,而无须格式化设置 xDoc.Save(Server.MapPath("~/xml/stus.xml")); ClientScript.RegisterStartupScript(this.GetType(), "", "alert(‘xml文件创建成功!‘)", true); }
通过上面的代码能再xml文件夹中创建一个stus.xml文件,内容如下:
<?xml version="1.0" encoding="utf-8"?> <students> <student num="S001"> <name>张三</name> <age>23</age> </student> <student num="S002"> <name>李四</name> <age>24</age> </student> <student num="S003"> <name>王五</name> <age>25</age> </student> </students>
2. 使用linq to xml 读取xml并在Reapter控件中显示相应数据
代码如下:
protected void btnShowXml_Click(object sender, EventArgs e) { ReapterBind(); } public void ReapterBind() { var xDoc = XDocument.Load(Server.MapPath("~/xml/stus.xml")); var result = from item in xDoc.Element("students").Elements() where Convert.ToInt32(item.Element("age").Value) > 23 select new { StuNum = item.Attribute("num").Value, StuName=item.Element("name").Value, StuAge = item.Element("age").Value }; this.rptStudents.DataSource = result; this.rptStudents.DataBind(); }
aspx中的代码如下:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="LinqToXmlTest.aspx.cs" Inherits="LinqToXmlTest" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> <asp:Button ID="btnGenerateXml" runat="server" Text="生成XML" OnClick="btnGenerateXml_Click" /> <asp:Button ID="btnShowXml" runat="server" Text="加载XML" Height="21px" OnClick="btnShowXml_Click" /> <br /> ----------------------------- <table border="1"> <tr> <th> 学号 </th> <th> 姓名 </th> <th> 年龄 </th> </tr> <asp:Repeater ID="rptStudents" runat="server"> <ItemTemplate> <tr> <td> <%#Eval("StuNum") %> </td> <td> <%#Eval("StuName") %> </td> <td> <%#Eval("StuAge") %> </td> </tr> </ItemTemplate> </asp:Repeater> </table> </div> </form> </body> </html>
标签:style blog http color 使用 io strong 文件
原文地址:http://www.cnblogs.com/tianguook/p/3928228.html