将datatable转换为XML

时间:2015-03-31 09:42:20

标签: c# asp.net-mvc linq

我将XML转换为datatable,现在又希望将数据表转换为XML。 我有数据库,其中有四个XML,并且必须更改该文本xml

public ActionResult getChangeContent(string arg, string content)
{
    char[] a = { ':' };
    string[] id = arg.Split(a);
    decimal tid = Convert.ToDecimal(id[0]);
    decimal jid = Convert.ToDecimal(id[1]);
    string groupname = id[2];
    var gp = (from Trans_Mast in r2ge.Transcription_Master where Trans_Mast.Transcription_Id == tid && Trans_Mast.Entity_Id == jid select Trans_Mast).Distinct();

    foreach (var g in gp)
    {
        DataSet ds = new DataSet();
        ds.ReadXml(new XmlTextReader(new StringReader(g.Text_xml)));
        DataTable text = ds.Tables[0];

        for (int i = 0; i < text.Rows.Count; i++)
        {
            if (text.Rows[i]["group"].Equals(groupname))
            {
                text.Rows[i]["Text_Text"] = content;
            }
            text.AcceptChanges();
        }
        ConvertDatatableToXML(text);
    }
    return View();
}

public string ConvertDatatableToXML(DataTable dtTemp)
{
    MemoryStream str = new MemoryStream();
    dtTemp.WriteXml(str, true);
    str.Seek(0, SeekOrigin.Begin);
    StreamReader sr = new StreamReader(str);
    string xmlstr;
    xmlstr = sr.ReadToEnd();
    return (xmlstr);
}

数据集已更改,但对XML没有任何影响..请提出任何建议..

1 个答案:

答案 0 :(得分:0)

使用这段代码:

private static string ConvertDataTableToXML(DataTable dtBuildSQL)    
{    
    DataSet dsBuildSQL = new DataSet();    
    StringBuilder sbSQL;    
    StringWriter swSQL;    
    string XMLformat;    

    sbSQL = new StringBuilder();    
    swSQL = new StringWriter(sbSQL);

    dsBuildSQL.Merge(dtBuildSQL, true, MissingSchemaAction.AddWithKey);    
    dsBuildSQL.Tables[0].TableName = “Table”;

    foreach (DataColumn col in dsBuildSQL.Tables[0].Columns)    
    {
        col.ColumnMapping = MappingType.Attribute;
    }

    dsBuildSQL.WriteXml(swSQL, XmlWriteMode.WriteSchema);
    XMLformat = sbSQL.ToString();
    return XMLformat;    
}