How to write C# DataSet object to XML with customized nodes structure?

211 views Asked by At

I have a similar case - I receive a DataSet object with data tables willed with data (e. g. customers table ...) from an external module (done by other programmer).

I then save the data set object to an xml using the writeXml method - here is my code

public void Save(string myXmlFilePath)
{        
    XmlWriterSettings settings = new XmlWriterSettings();
    settings.Encoding = System.Text.Encoding.UTF8; 
    settings.Indent = true;
    settings.NewLineHandling = NewLineHandling.None;

    using (XmlWriter writer = XmlWriter.Create(myXmlFilePath, settings))
    {
        ExportObject.WriteXml(writer);
        writer.Close();
    }
}

I get the standard xml file output structure like this:

<NewDataSet>
    <Customers>...</Customers>
    <Customers>...</Customers>
<NewDataSet>`

However I want the structure like this

<Customers>
    <Customer>...</Customer>
    <Customer>...</Customer>
</Customers>`

How can I achieve this?

2

There are 2 answers

3
Alexander Petrov On

Specify the desired names to the dataset and the tables within it.

ExportObject.DataSetName = "Customers";
ExportObject.Tables[0].TableName = "Customer";
0
LosManos On

A work around is to let WriteXml write however it likes and then do an XSD transform to the format you prefer.