Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dataSet.GetXml() doesn't return xml for null or blank columns

Tags:

c#

xml

dataset

xsd

When I call dataSet.GetXml() I don't get any xml returned for columns with null or blank values. Is there a simple, efficient way to get around this? An example of the problem below. Notice how a2 is missing from the second results section.

<results>
<a1>test1</a1>
<a2>test2</a2>
<a3>test3</a3>
</results>
<results>
<a1>Atest1</a1>
<a3>Atest3</a3>
</results>
like image 287
Ben Avatar asked Feb 04 '11 22:02

Ben


2 Answers

The problem is detailed in this Microsoft KB article: http://support.microsoft.com/default.aspx?scid=kb;EN-US;Q317961. See this previous SO question for more detail: DataSet.GetXml not returning null results.

I don't think there is a good solution to your direct question. Given context, there may be another way to approach the problem though.

like image 188
rmc00 Avatar answered Oct 02 '22 02:10

rmc00


One solution that worked for me.

First clone the DataTable, make all columns of type string, replace all null values with string.empty, then call GetXml on a new DataSet.

        DataTable dtCloned = dt.Clone();
        foreach (DataColumn dc in dtCloned.Columns)
            dc.DataType = typeof(string);
        foreach (DataRow row in dt.Rows)
        {
            dtCloned.ImportRow(row);
        }

        foreach (DataRow row in dtCloned.Rows)
        {
            for (int i = 0; i < dtCloned.Columns.Count; i++)
            {
                dtCloned.Columns[i].ReadOnly = false;

                if (string.IsNullOrEmpty(row[i].ToString()))
                    row[i] = string.Empty;
            }
        }

        DataSet ds = new DataSet();
        ds.Tables.Add(dtCloned);
        string xml = ds.GetXml();
like image 22
vlad Avatar answered Oct 02 '22 02:10

vlad