How to create a new xml file with XmlDocument?

This code will create new xml file from scratch. The file does not exist now and will be created with the help of the class XmlDocument.

Used Classes:


XML File:

<?xml version="1.0" encoding="utf-8"?>
  <Category ID="01">
    <Description>This is a list my XML articles.</Description>


<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Xml" %>
<%@ Page Language="C#" Debug="true" %>

<script  runat="server">
void Page_Load(object sender, System.EventArgs e){
        XmlDocument xmlDoc = new XmlDocument();

        // Write down the XML declaration
        XmlDeclaration xmlDeclaration = xmlDoc.CreateXmlDeclaration("1.0","utf-8",null);

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

        // Create a new <Category> element and add it to the root node
        XmlElement parentNode  = xmlDoc.CreateElement("Category");

        // Set attribute name and value!
        parentNode.SetAttribute("ID", "01");


        // Create the required nodes
        XmlElement mainNode  = xmlDoc.CreateElement("MainCategory");
        XmlElement descNode  = xmlDoc.CreateElement("Description");
        XmlElement activeNode  = xmlDoc.CreateElement("Active");

        // retrieve the text 
        XmlText categoryText= xmlDoc.CreateTextNode("XML");
        XmlText descText  = xmlDoc.CreateTextNode("This is a list my XML articles.");
        XmlText activeText  = xmlDoc.CreateTextNode("true");

        // append the nodes to the parentNode without the value

        // save the value of the fields into the nodes

        // Save to the XML file
        xmlDoc.Save( Server.MapPath("categories.xml"));

        Response.Write("XML file created");

Filed under:


# mmkk said:

there are something wrong in your demo when we want to apply multiple values.

Sunday, May 16, 2004 11:48 PM
# Sonu Kapoor said:

If you could tell me where then I could fix this.


Tuesday, May 18, 2004 4:47 PM