You may receive the error "This document already has a DocumentElement node." - Part II

In continuation to Part I of this article, we will examine how we can load the XML Fragment returned by the SQL FOR XML query, into a DataSet, to form a Well Formed XML Document.

SqlConnection objCon = new SqlConnection("Connection String");
SqlCommand objCmd = new SqlCommand("select * from customers for xml auto", objCon);
XmlReader xr = null;
XmlDocument xDoc = new XmlDocument();
DataSet ds = new DataSet();
try
{
objCon.Open();
xr = objCmd.ExecuteXmlReader();
ds.ReadXml(xr);
xDoc.LoadXml(ds.GetXml());
xDoc.Save(Server.MapPath("Test.xml"));
}
catch(Exception ex)
{
Response.Write(ex.Message);

}
finally
{
objCon.Close();
xr.Close();
}


As we can see the above code uses a DataSet to load the XML Fragment returned by the FOR XML Select query. The DataSet object is intelligent enough to append a ROOT Node to all XML Data that is being read into/written by it and hence the error "This document already has a DocumentElement node." can be avoided.

We will examine the other approaches in the next articles.

Read
Part III, Part IV of the series.

Cheers and Happy Programming !!!

Print | posted on Monday, September 19, 2005 9:02 AM

Comments on this post

# re: You may receive the error "This document already has a DocumentElement node." - Part II

Requesting Gravatar...
thanks for this post admin..
Left by mario oyunları on Sep 21, 2009 10:44 AM

# re: You may receive the error "This document already has a DocumentElement node." - Part II

Requesting Gravatar...
thanks admin good post.
Left by mario oyunları on Jan 08, 2010 3:19 AM

# re: You may receive the error "This document already has a DocumentElement node." - Part II

Requesting Gravatar...
thank you admin too mych
Left by Iso Propyl Alcohol on Mar 04, 2011 8:26 PM

# re: You may receive the error "This document already has a DocumentElement node." - Part II

Requesting Gravatar...
thnx, very useful
Left by Harvey on Aug 31, 2012 8:32 PM

Your comment:

 (will show your gravatar)