Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Problem with creating XML document

Status
Not open for further replies.
Jun 9, 2006
159
US
I'm getting this error when I run the code below. Here is my error:


Code:
This document already has a DocumentElement node. 
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.InvalidOperationException: This document already has a DocumentElement node.

Source Error: 


Line 267:            foreach(DataTable dt in ds.Tables){
Line 268:                foreach(DataRow dr in dt.Rows) {
Line 269:                    doc.AppendChild(AddSong(dr, songs));
Line 270:                }
Line 271:            }

Here is my source code:


Code:
        public string GetXML(int userId) {
            
            // create empty xml doc
            XmlDocument doc = new XmlDocument();
            XmlNode docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
            doc.AppendChild(docNode);

            // songs element
            XmlNode songs = doc.CreateElement("songs");
            doc.AppendChild(songs);

            DataSet ds = GetUserMp3s(userId);
            
            // add a song
            foreach(DataTable dt in ds.Tables){
                foreach(DataRow dr in dt.Rows) {
                    doc.AppendChild(AddSong(dr, songs));
                }
            }
    
            

            // Now create StringWriter object to get data from xml document.
            StringWriter sw = new StringWriter();
            XmlTextWriter xw = new XmlTextWriter(sw);
            doc.WriteTo(xw);

            return sw.ToString();
        }


private XmlNode AddSong(DataRow dr, XmlNode parent) {

            XmlNode song = XmlHelper.AddElement("song","song_Name",parent);
            XmlHelper.AddAttribute("mp3Id",dr["mp3Id"].ToString(),song);

            return song;

        }

I'm pretty new to workign with XML so I'm having problems figuring out this error. Can any offer any help?
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top