How to create attribute using XmlDocument in asp.net

XmlDocument CreateAttribute() - How to create attribute using XmlDocument
XmlDocumentCreateAttribute.aspx
<%@ Page Language="C#" AutoEventWireup="true" %>
<%@ Import Namespace="System.Xml" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
    void Button1_Click(object sender, System.EventArgs  e)
    {
        string xmlPath = Request.PhysicalApplicationPath + @"App_Data\aspbooks.xml";
        if (System.IO.File.Exists(xmlPath))
        {
            Label1.ForeColor = System.Drawing.Color.Red;
            Label1.Text = "Xml Document Already Exists!";
        }
        else
        {
            XmlDocument xmlDoc = new XmlDocument();

            XmlNode declarationNode = xmlDoc.CreateXmlDeclaration("1.0", "", "");
            xmlDoc.AppendChild(declarationNode);

            XmlNode booksNode = xmlDoc.CreateElement("books");
            xmlDoc.AppendChild(booksNode);

            XmlNode bookNode = xmlDoc.CreateElement("book");

            XmlAttribute categoryAttribute = xmlDoc.CreateAttribute("category");
            categoryAttribute.Value = "asp.net";
            bookNode.Attributes.Append(categoryAttribute);

            XmlNode bookTitleNode = xmlDoc.CreateElement("titleofbook");
            bookTitleNode.InnerText = "Secrets of Real World ASP.NET Dynamic Data Websites";
            bookNode.AppendChild(bookTitleNode);

            XmlNode bookAuthorNode = xmlDoc.CreateElement("bookauthor");
            bookAuthorNode.InnerText = "Craig Shoemaker";
            bookNode.AppendChild(bookAuthorNode);

            booksNode.AppendChild(bookNode);
            xmlDoc.Save(xmlPath);
            Label1.Text = "Xml Document Created Successfully!";
        }
    }
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>XmlDocument CreateAttribute() - How to create attribute using XmlDocument</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2 style="color:DarkBlue; font-style:italic;">XmlDocument Example: Using CreateAttribute() Method</h2>
        <hr width="575" align="left" color="SkyBlue" />
        <br /><br />
        <asp:Label 
            ID="Label1" 
            runat="server"
            Font-Bold="true"
            Text=""
            ForeColor="DeepPink"
            Font-Names="Comic Sans MS"
            Font-Size="X-Large"
            >
        </asp:Label>
        <br /><br />
        <asp:Button 
            ID="Button1"
            runat="server"
            OnClick="Button1_Click"
            Text="Create XmlDocument With Attribute Using XmlDocument"
            Height="42"
            Font-Bold="true"
            ForeColor="SaddleBrown"
            />
    </div>
    </form>
</body>
</html>








Related asp.net example