How to export a DataTable to Xml with ALL columns as attributes?

前端 未结 5 1630
执笔经年
执笔经年 2020-12-31 18:58

Question: I\'m exporting a System.Data.DataTable to XML. So far it works fine. But I want to have all the data in attributes, which works fine as well. But my problem now, i

5条回答
  •  温柔的废话
    2020-12-31 19:27

    It's a bit old thread but, maybe it can help someone:
    If you are not writing big xml files frequently (it's ok for exporting settings or something similar) you can use function below, otherwise it's better to use cutom xml schema.

    private static void addEmptyElementsToXML(DataSet dataSet)
    {
        foreach (DataTable dataTable in dataSet.Tables)
        {
            foreach (DataRow dataRow in dataTable.Rows)
            {
                for (int j = 0; j < dataRow.ItemArray.Length; j++)
                {
                    if (dataRow.ItemArray[j] == DBNull.Value)
                        dataRow.SetField(j, string.Empty);
                }
            }
        }
    }
    

    Usage:

    using(DataTable dTable = ..something..)
    using(DataSet dS = new DataSet())
    using(XmlTextWriter xmlStream = new XmlTextWriter("FILENAME.XML", Encoding.UTF8))
    {
        //set xml to be formatted so it can be easily red by human
        xmlStream.Formatting = Formatting.Indented;
        xmlStream.Indentation = 4;
    
        //add table to dataset
        dS.Tables.Add(dTable);
    
        //call the mentioned function so it will set all DBNull values in dataset
        //to string.Empty
        addEmptyElementsToXML(dS);
    
        //write xml to file
        xmlStream.WriteStartDocument();
        dS.WriteXml(xmlStream);
    }
    

提交回复
热议问题