Add DataRow to DataTable and Save as XML

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

My XML file has the following information:

-----------------------------------------------------------
<data>
<students>
<student>
<name>Rick James</name>
</student>
<student>
<name>Peter Gomez</name>
</student>
</students>
</data>
-----------------------------------------------------------

I use a DataSet to read the file and then attempt to add an extra <student>
as follows:

-----------------------------------------------------------
DataSet ds;
DataTable dt;
DataRow dr;

ds = new DataSet("data");
ds.ReadXml("data.xml");
dt = ds.Relations["students_student"].ChildTable;

dr = dt.NewRow();
dr["name"] = "Farty McSniff";
dt.Rows.Add(dr);

ds.AcceptChanges();
ds.WriteXml("data.xml");
-----------------------------------------------------------

The new <student> does NOT become a child of the <students> tag, instead it
gets added as a child of the <data> tag. Here's the output:

-----------------------------------------------------------
<data>
<students>
<student>
<name>Rick James</name>
</student>
<student>
<name>Peter Gomez</name>
</student>
</students>
<student>
<name>Farty McSniff</name>
<student>
</data>
-----------------------------------------------------------

My question: How do I make the new <student> a child of the <students> tag?

Thanks in advance,
-Fabricio
 
I figured it out... I wasn't taking into account the relationship between the
parent and child node. The DataSet automatically creates a hidden ID column
to represent the structural relationship found in the XML file. Setting the
hidden ID of the NewRow accordingly solved the problem.

-Fabricio
 
Back
Top