I'm using DataSet.ReadXml()
to import an XML file into a new DataSet. Then I'm adding a new row to one of the tables inside the DataSet, and then I want to export that DataSet to XML again. The problem is that the new row is not nested properly and just gets appended to the end of the XML file.
Here is the program:
using System;
using System.Data;
using System.IO;
using System.Xml;
public class Program
{
public static void Main()
{
string xml = @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?>
<DATAPACKET Version=""2.0"">
<METADATA>
<FIELDS>
<FIELD attrname=""CompanyID"" fieldtype=""string"" WIDTH=""10""/>
<FIELD attrname=""Description"" fieldtype=""string"" WIDTH=""40""/>
</FIELDS>
<PARAMS/>
</METADATA>
<ROWDATA>
<ROW CompanyID=""CC"" Description=""Contoso""/>
</ROWDATA>
</DATAPACKET>
";
XmlReader reader = XmlReader.Create(new StringReader(xml));
DataSet dataSet = new DataSet();
dataSet.ReadXml(reader, XmlReadMode.InferTypedSchema);
var rowTable = dataSet.Tables["ROW"];
var newRow = rowTable.NewRow();
newRow["CompanyID"] = "APPL";
newRow["Description"] = "Apple";
rowTable.Rows.Add(newRow);
Console.WriteLine(dataSet.GetXml());
}
}
And here is the output:
<DATAPACKET Version="2.0">
<METADATA>
<PARAMS />
<FIELDS>
<FIELD attrname="CompanyID" fieldtype="string" WIDTH="10" />
<FIELD attrname="Description" fieldtype="string" WIDTH="40" />
</FIELDS>
</METADATA>
<ROWDATA>
<ROW CompanyID="CC" Description="Contoso" />
</ROWDATA>
</DATAPACKET>
<ROW CompanyID="APPL" Description="Apple" />
What I want is for the new row to be nested with the other rows from that table like this:
<DATAPACKET Version="2.0">
<METADATA>
<PARAMS />
<FIELDS>
<FIELD attrname="CompanyID" fieldtype="string" WIDTH="10" />
<FIELD attrname="Description" fieldtype="string" WIDTH="40" />
</FIELDS>
</METADATA>
<ROWDATA>
<ROW CompanyID="CC" Description="Contoso" />
<ROW CompanyID="APPL" Description="Apple" />
</ROWDATA>
</DATAPACKET>
What am I doing wrong?
How do I get well formed XML out of DataSet.GetXml()
?