先拼接出字符串然后写入文件,
string fileName = @"D:XXX.xml"; //header StringBuilder xmlResult = new StringBuilder("<?xml version="1.0" encoding="UTF-8"?>"); xmlResult.Append("<ns0:SHIPMENT_DATA xmlns:ns0="http://xxx/v1.0">"); //CNTRLAREA xmlResult.Append("<CNTRLAREA>"); xmlResult.Append("<SENDER>"); xmlResult.Append("<LOGICALID>WQQQ</LOGICALID>"); xmlResult.Append("</SENDER>"); xmlResult.Append("</CNTRLAREA>"); //detail string sql = "SELECT 'jinwei' as name1,'jinwei2' as name2 "; DataTable dt = db.GetDataTable(sql); xmlResult.Append("<DETAILS>"); for (int i = 0; i < dt.Rows.Count; i++) { xmlResult.Append("<DETAIL>"); for (int j = 0; j < dt.Columns.Count; j++) { xmlResult.AppendFormat("<{0}>{1}</{2}>", dt.Columns[j].ToString(), dt.Rows[i][j].ToString(), dt.Columns[j].ToString()); } xmlResult.Append("</DETAIL>"); } xmlResult.Append("</DETAILS>"); xmlResult.Append("</ns0:SHIPMENT_DATA>"); //写入文件 try { //1.创建文件流 FileStream fileStream = new FileStream(fileName, FileMode.Create); //2.创建写入器 StreamWriter streamWriter = new StreamWriter(fileStream); //3.将内容写入文件 streamWriter.WriteLine(xmlResult); //4.关闭写入器 streamWriter.Close(); //5.关闭文件流 fileStream.Close(); } catch (Exception e) { }