Tuesday, September 8, 2009

How to update content of XML file using C#

Suppose the structure of an XML file is as of following type,

Now in order to add content or to update the content of the XML file, following is the code which will tell you how to do that,

public static bool SetPreferences(string filepath, string username, bool timeline, bool defects, bool processaudit, bool efforts, bool workprocessstatus)

{

int flag = 0;

bool check = false;

try

{

XDocument doc = XDocument.Load(filepath);

var query = from c in doc.Elements("users").Elements("user") select c;

foreach (XElement str in query)

{

if (str.Attribute("name").Value == username)

{

str.SetElementValue("timeline", timeline.ToString());

str.SetElementValue("defects", defects.ToString());

str.SetElementValue("processaudit", processaudit.ToString());

str.SetElementValue("efforts", efforts.ToString());

str.SetElementValue("workprocessstatus", workprocessstatus.ToString());

flag = 1;

}

}

if (flag == 0)

{

doc.Element("users").Add(new XElement("user", new XAttribute("name", username),new XElement("timeline", timeline.ToString()),new XElement("defects", defects.ToString()),new XElement("processaudit", processaudit.ToString()),

new XElement("efforts", efforts.ToString()),

new XElement("workprocessstatus", workprocessstatus.ToString())));

}

doc.Save(filepath);

check = true;

return check;

}

catch

{

return check;

throw;

}

}

Now using this code you will be able to read and write into the XML file.

Always find results on Fukat Ka Gyan !!! to save your time…

No comments:

Post a Comment