如何从数据表中拆分字段

时间:2014-03-24 13:34:42

标签: c# asp.net xml datatable dataset

我有一个包含xml格式数据的网址。请参阅我的代码: -

public partial class WebForm1 : System.Web.UI.Page
{
   protected void Page_Load(object sender, EventArgs e)
   {
      if (!IsPostBack)
      {
         GridData();
      }
   }

   protected void GridData()
   {
      string url = "http://s3.amazonaws.com/webassets.ticketmob.com/feeds/31squares/tunestub-XML.xml";

      XmlDocument doc = new XmlDocument();
      DataSet ds = new DataSet();
      DataTable dt = new DataTable();
      ds.ReadXml(url);
      dt = ds.Tables[1];

      grid.DataSource = ds.Tables[1];
      grid.DataBind();
   }
   public override void VerifyRenderingInServerForm(Control control)
   {
   }
   protected void btnExport_Click(object sender, EventArgs e)
   {
      Response.ClearContent();
      Response.Buffer = true;
      Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "ExportVenue.xls"));
      Response.ContentType = "application/ms-excel";
      StringWriter sw = new StringWriter();
      HtmlTextWriter htw = new HtmlTextWriter(sw);

      GridData();

      for (int i = 0; i < grid.HeaderRow.Cells.Count; i++)
      {
         grid.HeaderRow.Cells[i].Style.Add("background-color", "#df5015");
      }
      grid.RenderControl(htw);
      Response.Write(sw.ToString());
      Response.End();
   }
}

这给了我xls文件中的数据,但我想添加一个新的列名&#34; Event&#34; &安培;需要来自xml的特定列,如我想要&#34; name&#34;,&#34; address&#34;。 怎么可能?请帮帮我...

2 个答案:

答案 0 :(得分:0)

在数据表中构建数据之后。在数据表中添加这些新列,如下所示 -

DataColumn nameCol = datatable.Columns.Add("Name", typeof(string));
nameCol.AllowDBNull = false;

参考:http://msdn.microsoft.com/en-us/library/hfx3s9wd(v=vs.110).aspx 然后通过for循环或现有查询从现有列中提取所需数据。

答案 1 :(得分:0)

尝试使用此示例实现:

问题1:添加新列名称&#34;事件&#34;

string path=Application.StartupPath + @"\Test.xml";
XmlWriter writer = XmlWriter.Create(path);
XmlDocument doc = new XmlDocument();
doc.Load(path);
writer.WriteStartElement("Event");
writer.WriteString("Event Decription");
writer.WriteEndElement();
writer.WriteEndElement();
writer.WriteEndDocument();
writer.Close();

问题2:从xml获取特定列

对于唯一列:

XmlNodeList elemnt1 = doc.GetElementsByTagName("name");
XmlNodeList elemnt2 = doc.GetElementsByTagName("address");

如果有多个具有相同名称的列:

XmlNodeList elem1 = doc.GetElementsByTagName("name");
 for (int j = 0; j < elem1 .Count; j++)
     {
          if (elem1[j].InnerText == "name")
                 {
                    //want u want to do
                  }
      }