User Id :    Password :      New Member   Forgot Password  
Topic: How to write code in XML?
Anamika singh
23 Nov 2010 at 02:07 AM
How to write code in XML?
Re: How to write code in XML?
Gaurav
16 Dec 2010 at 03:48 AM
Save that file as "sample.xml" in the /App_Data sub-folder of your ASP.NET Placing the XML file in /App_Data sub-folder ensures that no one will be able to directly access this file from the web. It will only be accessed by our ASP.NET page which will read and display its contents.
<?xml version="1.0" encoding="utf-8"?>
<article>
    <author isadmin="true">Faisal Khan</author>
    <title>Sample XML Document</title>
    <body>The body of the article goes here.</body>
</article>
Reading the Contents of XML File using XmlDocument class
System.Xml namespace has a class with the name of XmlDocument which we will use to read XML file's contents and display it to the user. Reading the contents of sample.xml file is as easy as these two lines:
    XmlDocument doc = new XmlDocument();
    doc.Load(Server.MapPath("~/App_Data/sample.xml"));
Before we deliver ourselves deeper into the code, we should create the ASP.NET page first and study its code later.
Reader.aspx
Copy and paste following code into an ASP.NET page and then save it as "reader.aspx":
<%@ Page Language="C#" AutoEventWireup="true" %>

<%@ Import Namespace="System.Xml" %>

<script runat="server">
protected void Page_Load(object source, EventArgs e)
{
    XmlDocument doc = new XmlDocument();
    doc.Load(Server.MapPath("~/App_Data/sample.xml"));

    XmlNode root = doc.DocumentElement;
    AuthorLiteral.Text = root.SelectSingleNode("author").ChildNodes[0].Value;
    TitleLiteral.Text = root.SelectSingleNode("title").ChildNodes[0].Value;
    BodyLiteral.Text = root.SelectSingleNode("body").ChildNodes[0].Value;
}
</script>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Reading an XML File</title>
    <style type="text/css">
        body { font-family: Verdana; font-size: 9pt; }
        .name { background-color: #F7F7F7; }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <table width="50%" cellpadding="5" cellspacing="2">
        <tr>
            <td class="name">Name</td>
            <td><asp:Literal ID="AuthorLiteral" runat="server" />
            <asp:Literal ID="AdminLiteral" runat="server" /></td>
        </tr>
        <tr>
            <td class="name">Title</td>
            <td><asp:Literal ID="TitleLiteral" runat="server" /></td>
        </tr>
        <tr>
            <td class="name">Body</td>
            <td><asp:Literal ID="BodyLiteral" runat="server" /></td>
        </tr>
        </table>

    </div>
    </form>
</body>
</html>
Total Replies: 1
 
Featured Text Ad

Featured Ad