Add DataRow to DataTable and Save as XML

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
 
G

Guest

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top