Search code examples
c#asp.netxmldataset

Dataset to xml Null Values


I have the code below, where from 3 tables I take the data and write an xml.
I want write (when a record column has null value) the column on the xml with null value. For example if (Category_name == Null ) to write on the xml (Null) Right now the code skip the column and don’t even have this column on the xml.

 string xmlFileData = "";

    string[] tables = new string[] { "category",  "company", "config" };
    string query;
    xmlFileData += "<MyXml>";
    SqlConnection conn;
    dbconnect obj;
    obj = new dbconnect();//initailizing class object
    for (int i = 0; i < tables.Length; i++)
    {
        string ifemptquery;
        DataSet ds = new DataSet();

        DataSet ds1 = new DataSet();
        conn = obj.getConnection(); //calling connection function

        ifemptquery = "SELECT * FROM " + tables[i] ";
        SqlCommand cmd1 = new SqlCommand(ifemptquery, conn);
        conn.Open();
        SqlDataAdapter da1 = new SqlDataAdapter(cmd1);
        DataTable dt1 = new DataTable();
        da1.Fill(dt1);
        conn.Close();
        if (dt1.Rows.Count > 0)
        {
            query = "SELECT * FROM " + tables[i] ";
            SqlCommand cmd = new SqlCommand(query, conn);
            conn.Open();
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            da.Fill(ds);
            conn.Close();
            conn.Dispose();
            ds.DataSetName = tables[i];
            string vartbname = tables[i];
            string trimed_tbname = vartbname.Replace("_", "");
            ds.Tables[0].TableName = trimed_tbname;
            xmlFileData += ds.GetXml();
        }
        else
        {

        }


    }
    xmlFileData += "</MyXml>";
    File.WriteAllText(Server.MapPath("~/xmlbackup/") + "Backup.xml", xmlFileData);

Solution

  • Refer similar question here - dataSet.GetXml() doesn't return xml for null or blank columns

    Apart from solutions mentioned there, you can also traverse through dataset and write XML using XmlTextWriter. This method is not recommended if you are dealing with huge data.