根据DataTable 创建 XML
//读Xml至DataTable
private void butInputXml_Click(object sender, EventArgs e)
{
DataSet ds = new System.Data.DataSet();
ds.ReadXml(this.txtXmlFile.Text);
DataTable dt = ds.Tables[0];
this.dataGridView1.DataSource = dt;
}
//保存Xml
private void butSaveXml_Click(object sender, EventArgs e)
{
DataTable dt = (DataTable)this.dataGridView1.DataSource;
m_CreateXml(this.txtXmlFile.Text,dt);
}
//根据DataTable 创建 XML
private void m_CreateXml(string strXmlFile,DataTable dt)
{
System.Xml.XmlTextWriter xmlWriter;
string strFilename = strXmlFile;
xmlWriter = new System.Xml.XmlTextWriter(strFilename, Encoding.Default);//创建一个xml文档
xmlWriter.Formatting = System.Xml.Formatting.Indented;
xmlWriter.WriteStartDocument();
xmlWriter.WriteStartElement("handler");
for (int i = 0; i < dt.Rows.Count-1; i++)
{
xmlWriter.WriteStartElement("flow");
for (int j = 0; j < dt.Columns.Count - 1; j++)
{
xmlWriter.WriteStartElement(dt.Columns[j].Caption);
xmlWriter.WriteString(dt.Rows[i][j].ToString());
xmlWriter.WriteEndElement();
}
xmlWriter.WriteEndElement();
}
xmlWriter.WriteEndElement();
xmlWriter.Close();
}