Wednesday, August 8, 2012

Create XML document programatically in C#


XmlDocument XD = new XmlDocument();
            XmlNode declaration = XD.CreateNode(XmlNodeType.XmlDeclaration, null, null);
            XD.AppendChild(declaration);

            XmlNode student = XD.AppendChild(XD.CreateElement("student"));

            XmlNode name = student.AppendChild(XD.CreateElement("name"));
            name.InnerText = "prasad";

            XmlNode dept = student.AppendChild(XD.CreateElement("dept"));
            dept.InnerText = "information tech";

            XmlNode id = student.AppendChild(XD.CreateElement("id"));
            id.InnerText = "1324";         
            XD.Save("student.xml");
              (OR)
            string data = XD.OuterXml;

OutPut: 

<?xml version="1.0"?>

<student>
 <name>prasad</name>
 <dept>information tech</dept>
 <id>1324</id>
</student>