Click to See Complete Forum and Search --> : Add Table to XML file using DataSet...


gcetti
December 17th, 2008, 02:53 PM
Hello,

I am try to edit an xml file via DataSet in my C# app, by adding a new table to the structure with multiple nodes to the structure - but the table should be a child table of one of the existing Tables in the structure I have read in.

In other words:
<ParentTable>
<Data1>FOO</Data1>
</ParentTable>

Should end up like this:
<ParentTable>
<Data1>FOO</Data1>
<MyChildTable>
<Test>BAR</Test>
</MyChildTable>
</ParentTable>

I'm having problems getting the table in the correct place when I write the XML after I change it. I am adding the table/fields/records, and setting up the relations, but for some reason when I process the xml the new table I have added just appends to the end of the xml file and doesnt appear in the branch where it should.

Here is the code snippet of what I'm doing:

XmlTextReader xmlreader1 = new XmlTextReader("Test.xml");

DataSet ds = new DataSet();
ds.ReadXml(xmlreader1);

DataTable newTable = new DataTable();
newTable.TableName = "MyChildTable";
newTable.Columns.Add( "NewField" );
newTable.Columns.Add( "ParentTable_ID",System.Type.GetType("System.Int32") );
ds.Tables.Add( newTable );

ds.Tables["MyChildTable"].ParentRelations.Add( "MyChildTable", ds.Tables["ParentTable"].Columns["ParentTable_ID"], ds.Tables["MyChildTable"].Columns["ParentTable_ID"], true);

DataRow newRow;
newRow = ds.Tables["MyChildTable"].NewRow();
newRow["Test"] = "Value";
newRow["ParentTable_ID"] = "1";
ds.Tables["MyChildTable"].Rows.Add(newRow);

ds.AcceptChanges();

StreamWriter myStreamWriter = new StreamWriter("Out.xml" );
ds.WriteXml(myStreamWriter);
myStreamWriter.Close();



Can anyone see what I am doing incorrectly or have any suggestions?

Thanks,
Greg
greg@ram-software.com

TheCPUWizard
December 17th, 2008, 02:58 PM
1) Please edit your existing post to use code tags [ code] and [ /code]

2) Create a valid, XML with the information in place. Then load this into a dataset and write the Schema. Use this as the schema to create your actual DataSet.