CodeKicks.com
Focus on Microsoft Technologies - Tutorials, Articles, Code Samples.

Tuesday, April 10, 2007

Reading and Writing XML files using C# .NET

using System.Xml;

void WriteXML()
{
try
{
//pick whatever filename with .xml extension
string filename = "XML"+DateTime.Now.Day + ".xml";

XmlDocument xmlDoc = new XmlDocument();

try
{
xmlDoc.Load(filename);
}
catch(System.IO.FileNotFoundException)
{
//if file is not found, create a new xml file
XmlTextWriter xmlWriter = new XmlTextWriter(filename, System.Text.Encoding.UTF8);
xmlWriter.Formatting = Formatting.Indented;
xmlWriter.WriteProcessingInstruction("xml", "version='1.0' encoding='UTF-8'");
xmlWriter.WriteStartElement("Root");
//If WriteProcessingInstruction is used as above,
//Do not use WriteEndElement() here
//xmlWriter.WriteEndElement();
//it will cause the <Root> to be &ltRoot />
xmlWriter.Close();
xmlDoc.Load(filename);
}
XmlNode root = xmlDoc.DocumentElement;
XmlElement childNode = xmlDoc.CreateElement("childNode");
XmlElement childNode2 = xmlDoc.CreateElement("SecondChildNode");
XmlText textNode = xmlDoc.CreateTextNode("hello");
textNode.Value = "hello, world";

root.AppendChild(childNode);
childNode.AppendChild(childNode2);
childNode2.SetAttribute("Name", "Value");
childNode2.AppendChild(textNode);

textNode.Value = "replacing hello world";
xmlDoc.Save(filename);
}
catch(Exception ex)
{
WriteError(ex.ToString());
}
}

void WriteError(string str)
{
outputBox.Text = str;
}

Post a Comment

Anonymous said...

can't able to understand

Anonymous said...

its ok.it is hardcore coding.
i want to extract value and set/write to xml file by using c#.
say text from textbox how can i do it.

Microsoft .NET Support Team said...

Please provide your details like email id. we respond to your quries.

Subscribe to site Feed
http://feeds.feedburner.com/Microsoftnet
Microsoft .NET Support

Ragu said...

I implemented this. Thanks for the code.

Anonymous said...

m

someRandomGuy said...

Is this code being cut off by the div its in? In my IE I can't see the compete code- it's in too narrow of a container :(.

Anonymous said...

I too was not able to see some charector at righ side of the windows.

But I was able to copy and paste the full content.

Thanks,
George

Anonymous said...

hi this article really solved my stuff .
thanks
Ravi Kore