前端之家收集整理的这篇文章主要介绍了
DataTable 写入XML 并输出到前台,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
一、前台代码
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!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>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function(){
$.post("Default.aspx?action=getXML",function(xml){
var trArr=[];
$(xml).find("MatrixInfo").each(function(){
var id = $(this).find("ID").text();
var name = $(this).find("Name").text();
trArr.push("<tr><td>"+id+"</td><td>"+name+"</td></tr>");
});
$("#tbodyList").html(trArr.join(""));
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<table style="width:200px;" border="1">
<thead><tr><td>ID</td><td>Name</td></tr></thead>
<tbody id="tbodyList" ></tbody>
</table>
</div>
</form>
</body>
</html>
二、后台代码
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections.Generic;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender,EventArgs e)
{
if(Request["action"]=="getXML")
BuilderXML();
}
private void BuilderXML()
{
List<Person> list = new List<Person> {
new Person(){Id=1,Name="小明'\"}><,\\/~"},new Person(){Id=2,Name="小华"}
};
DataTable dt = new DataTable("MatrixInfo");
DataColumn dc1 = new DataColumn("ID");
DataColumn dc2 = new DataColumn("Name");
dt.Columns.Add(dc1);
dt.Columns.Add(dc2);
foreach (Person p in list)
{
DataRow dr = dt.NewRow();
dr["ID"] = p.Id;
dr["Name"] = p.Name;
dt.Rows.Add(dr);
}
DataTableWriteXML(dt);
}
private void DataTableWriteXML(DataTable dt)
{
System.IO.StringWriter writer = new System.IO.StringWriter();
dt.WriteXml(writer);
string xmlstr = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" + writer.ToString();
Response.ContentType = "text/xml";
Response.Charset = "UTF-8";
System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
doc.LoadXml(xmlstr);
doc.Save(Response.OutputStream);
Response.End();
}
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
}
}
原文链接:https://www.f2er.com/xml/298118.html