Thursday, December 16, 2010

C# write xml file using XmlDocument class

step1.

using System.Xml;
//...
//something
//...
//Declaration
XmlDocument xmldoc;
XmlElement xmlelem;
XmlElement xmlelem2;
XmlText xmltext;
//....
//something
//....

xmldoc = new XmlDocument();
XmlDeclaration declaration = xmldoc.CreateXmlDeclaration("1.0", "utf-8", null);
xmldoc.AppendChild(declaration);

xmlelem = xmldoc.CreateElement("Root");
xmlelem.SetAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
xmlelem.SetAttribute("xmlns:xsd", "http://www.w3.org/2001/XMLSchema");
xmldoc.AppendChild(xmlelem);
//Language
xmlelem2 = xmldoc.CreateElement("Language");
xmltext = xmldoc.CreateTextNode("English");
xmlelem2.AppendChild(xmltext);
xmldoc.ChildNodes.Item(1).AppendChild(xmlelem2);
//Author
xmlelem2 = xmldoc.CreateElement("Author");
xmltext = xmldoc.CreateTextNode("WayToVC");
xmlelem2.AppendChild(xmltext);
xmldoc.ChildNodes.Item(1).AppendChild(xmlelem2);

//saving
try
{
xmldoc.Save("SomeFile.xml");//I've chosen the c:\ for the resulting file somefile.xml
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}

//

You can add subchilds using xmldoc.CreateElement() method and append the element to the parent.

No comments: