In this article we are explaining how to read and
write Xml file data in Asp.net. To use xml file in asp.net we have to use two namespace
'System.Text' and 'System.Xml' then follow this steps.
Step
1
Add an Xal file in your project by using 'Add new item'.
Then write following code. Xml code can be change according to your need.
<?xml version="1.0" encoding="utf-8"?>
<EmployeeData>
<Details>
<Name>Jown</Name>
<Address>Delhi</Address>
<Mobile>740579959</Mobile>
</Details>
</EmployeeData>
Step
2
In 'Default.aspx' add following control.
<form id="form1" runat="server">
<asp:Label ID="lblName" runat="server" Text="Name:"></asp:Label>
<asp:TextBox ID="TextName" runat="server" ></asp:TextBox>
<asp:Label ID="lblAdd" runat="server" Text="Address:"></asp:Label>
<asp:TextBox ID="TextAdd" runat="server" ></asp:TextBox>
<asp:Label ID="lblMob" runat="server" Text="Mobile:"></asp:Label>
<asp:TextBox ID="TextMob" runat="server" ></asp:TextBox>
<asp:Button ID="WriteXml" runat="server" Text="WriteXml" OnClick="WriteXml_Click" />
<asp:Button ID="ReadXml" runat="server" Text="ReadXml" OnClick="ReadXml_Click" />
<asp:Label ID="lblMsg" runat="server" Text=""></asp:Label>
</form>
Step
3
In 'Default.aspx.cs' page add following cod
using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Text;
using
System.Web;
using
System.Web.UI;
using
System.Web.UI.WebControls;
using
System.Xml;
public partial class XmlReadWrite : System.Web.UI.Page
{
protected void Page_Load(object
sender, EventArgs e)
{
}
protected void WriteXml_Click(object sender, EventArgs e)
{
XmlTextWriter writeXml = new XmlTextWriter(Server.MapPath("EmpData.xml"), Encoding.UTF8);
writeXml.WriteStartDocument();
writeXml.WriteStartElement("EmployeeData");
writeXml.WriteStartElement("Details");
writeXml.WriteElementString("Name", TextName.Text);
writeXml.WriteElementString("Address",
TextAdd.Text);
writeXml.WriteElementString("Mobile", TextMob.Text);
writeXml.WriteEndElement();
writeXml.WriteEndElement();
writeXml.WriteEndDocument();
writeXml.Close();
}
protected void ReadXml_Click(object sender, EventArgs e)
{
{
string parentElement = "";
string childElement = "";
string childValue = "";
bool element = false;
lblMsg.Text = "";
XmlTextReader readXml = new XmlTextReader(Server.MapPath("EmpData.xml"));
while (readXml.Read())
{
if (readXml.NodeType == XmlNodeType.Element)
{
if (element)
{
parentElement = parentElement + childElement + "<br>";
}
element = true;
childElement = readXml.Name;
}
else if (readXml.NodeType == XmlNodeType.Text | readXml.NodeType == XmlNodeType.CDATA)
{
element = false;
childValue = readXml.Value;
lblMsg.Text = lblMsg.Text + "<b>" +
parentElement + "<br>" + childElement + "</b><br>" + childValue;
parentElement = "";
childElement = "";
}
}
readXml.Close();
}
}
}
Step
4
Finally run project. Click on 'WriteXml' to write xml
and click on 'ResdXml' to read xml.
No comments:
Post a Comment