Search code examples
c#.netxmllinq-to-xmlwritexml

Create write and save xml file dynamically in c# .net


I want to create xml file and write data from database in it. file will be created dynamically.

I am storing data in DataTable. Query is select documentId,documentContent from tblDocument where status = 'F'

where documentContent is xml data.

I have tried following code but its not working,

foreach(DataRow dr in dt.Rows)
{
    string filepath =  ConfigurationManager.Appsetings[Constants.FailedDocuments];
    string filename = "message_"+ dr["documentId"].ToString();
    string content = dr["documentContent"].ToString();
    XDocument xdoc = new XDocument();
    xdoc.parse(content);
    xdoc.Load(filepath+filename);
}

I am new to this and don't know how to and where to place this code correctly as i want to write content


Solution

  • Two thing:

    1. Please post correct code. The XDocument class has no instance method "parse", only "Parse". The XDocument class has no instance method "Load", only static method "Load".
    2. xdoc.Parse(content) would create a XDocument from the string. XDocument.Load(filename) would return a XDocument loaded from the XML file "filename".

    This would do the job:

    foreach(DataRow dr in dt.Rows) {
       string filepath =  ConfigurationManager.Appsetings[Constants.FailedDocuments];
       string filename = "message_"+ dr["documentId"].ToString();
       string content = dr["documentContent"].ToString();
       XDocument xdoc = new XDocument();
       xdoc.Parse(content);
       xdoc.Save(filepath+filename);
    }