Tuesday, October 02, 2007

Creating a new XML file using XMLDocument

Here is the XML file:

<?xml
version="1.0" encoding="utf-8"?>
<Students>
  <Student>
    <id>1</
id>
    <name>Michael Jones</
name>
  </Student>
</Students>


Here is the code to generate the XML file:


using System.Xml;



XmlDocument xmlDoc = new XmlDocument();
XmlDeclaration xmlDeclaration = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", null);

// Create the root element
XmlElement rootNode = xmlDoc.CreateElement(
"Students");
xmlDoc.InsertBefore(xmlDeclaration, xmlDoc.DocumentElement);
xmlDoc.AppendChild(rootNode);

// Creating the parent node
XmlElement parentNode = xmlDoc.CreateElement(
"Student");
xmlDoc.DocumentElement.AppendChild(parentNode);

// Create the required nodes
XmlElement eleId = xmlDoc.CreateElement(
"id");
XmlElement eleName = xmlDoc.CreateElement(
"name");

// retrieve the text
XmlText textId = xmlDoc.CreateTextNode("1");
XmlText textName = xmlDoc.CreateTextNode("Michael Jones");

// append the nodes to the parentNode without the value
parentNode.AppendChild(eleId);
parentNode.AppendChild(eleName);

// save the value of the fields into the nodes
eleId.AppendChild(textId);
eleName.AppendChild(textName);

xmlDoc.Save(Request.MapPath() + "Students.xml");

No comments:

Post a Comment