Showing posts with label XML. Show all posts
Showing posts with label XML. Show all posts

Read XML file in datatable and bind to datalist in asp.net

Description:-

In this article we will see about how to read Xml File in Datatable and bind into datalist in dotnet. Here I have created student xml file and bind into datalist. Here notice that XML file should be physical location t means in your project so we can read it using server method.

Design.aspx:-

    <div>
        <div>
            <asp:Button ID="Button1" runat="server" Text="Click To Read XML" OnClick="Button1_Click" />
        </div>
        <asp:DataList ID="DataList1" runat="server" BackColor="White" BorderColor="#3366CC"
            BorderStyle="None" BorderWidth="1px" CellPadding="4" GridLines="Both">
            <ItemStyle BackColor="White" ForeColor="#003399" />
            <ItemTemplate>
                Id :
                <asp:Label ID="Label1" runat="server" Text='<%# Eval("id") %>'></asp:Label><br />
                Name :
                <asp:Label ID="Label2" runat="server" Text='<%# Eval("name") %>'></asp:Label><br />
                Address :
                <asp:Label ID="Label3" runat="server" Text='<%# Eval("address") %>'></asp:Label>
            </ItemTemplate>
        </asp:DataList>
    </div>

Default.aspx.cs:-

        public void Button1_Click(object sender, EventArgs e)
        {
            DataTable objDataTable = new DataTable();
            string filepathe = @"XMLFile\XMLFile1.xml";
            objDataTable = ReadXMLFile1(filepathe);
            DataList1.DataSource = objDataTable;
            DataList1.DataBind();
        }

        public DataTable ReadXMLFile1(string filePath)
        {
            DataSet objds = new DataSet();
            objds.ReadXml(Server.MapPath(filePath));
            return objds.Tables[0];
        }

XML File:-

<students>
  <student>
    <id>1</id>
    <name>Umesh Patel</name>
    <address>Ahmedabad</address>
  </student>
  <student>
    <id>2</id>
    <name>Kirit Patel</name>
    <address>Ahmedabad</address>
  </student>
  <student>
    <id>1</id>
    <name>Harpalshinh Gohil</name>
    <address>Ahmedabad</address>
  </student>
  <student>
    <id>1</id>
    <name>Chirag Patel</name>
    <address>Ahmedabad</address>
  </student>
</students>

Output:-

How to Bind DataList from XML File Dynamically in Asp.Net

Description:-

The Data list Web server control displays data in a format that you can define using templates and styles. The Data List control is useful for data in any repeating structure, such as a table. The Data List control can display rows in different layouts, such as ordering them in columns or rows.
AlternatingItemTemplate
The contents of this template are displayed for every other row rendered by the GridView
EditItemTemplate
The contents of this template are displayed when a row is selected for editing
FooterTemplate
The contents of this template are displayed in the column footer
HeaderTemplate
The contents of this template are displayed in the column header
InsertTemplate
The contents of this template are displayed when a new data item is inserted
ItemTemplate
The contents of this template are displayed for every row rendered by the GridView
We can create TemplateFields in the GridView control using <TemplateField> element. Steps to create the <TemplateField> element in the GridView control

Declare the GridView and set the AutoGenerateColumns property to 'false'.
Create a Template column using <asp: TemplateField> tag within the <Columns> element.
Create <ItemTemplate> within the <asp: TemplateField> element to display value of field as text.
Create <EditItemTemplate> to display TextBox control to modify value of field when editing the record.

Now  Create Webpage and Drag GridView Control and Add Property what you need for Column.

<div>
   <asp:DataList ID="DataList1" runat="server" BackColor="Gray" BorderColor="#B40431"
      BorderStyle="None" BorderWidth="2px" CellPadding="3" CellSpacing="2" Font-Names="Verdana" Font-Size="Small" GridLines="Both" RepeatColumns="3" RepeatDirection="Horizontal"Width="600px">
      <FooterStyle BackColor="#F7DFB5" ForeColor="#0101DF" />
      <HeaderStyle BackColor="#6E6E6E" Font-Bold="True" Font-Size="Large" ForeColor="#868A08" BorderStyle="Groove" HorizontalAlign="Center" VerticalAlign="Middle" />
      <HeaderTemplate>
         Employee Details
      </HeaderTemplate>
      <ItemStyle BackColor="#BDBDBD" ForeColor="#000000" BorderWidth="2px" />
      <ItemTemplate>
         <b>Employee ID:</b>
         <asp:Label ID="Label1" runat="server" Text='<%# Bind("empid") %>'></asp:Label>
         <br />
         <b>Employee Name:</b>
         <asp:Label ID="lblCName" runat="server" Text='<%# Bind("name") %>'></asp:Label>
         <br />
         <b>Designation:</b>
         <asp:Label ID="lblName" runat="server" Text='<%# Bind("designation") %>'></asp:Label>
         <br />
         <b>City:</b>
         <asp:Label ID="lblCity" runat="server" Text=' <%# Bind("city") %>'></asp:Label>
         <br />
         <b>Country:</b>
         <asp:Label ID="lblCountry" runat="server" Text='<%# Bind("country") %>'></asp:Label>
         <br />
      </ItemTemplate>
   </asp:DataList>
</div>

Now create your XML File Like below what I have done.

<?xml version="1.0" encoding="utf-8"?>
<EmployeeDetails>
   <Employee>
      <empid>1001</empid>
      <name>Umesh</name>
      <designation>Software Engineer</designation>
      <city>Ahmedabad</city>
      <country>India</country>
   </Employee>
   <Employee>
      <empid>1002</empid>
      <name>Suresh</name>
      <designation>Web Developer</designation>
      <city>New Delhi</city>
      <country>India</country>
   </Employee>
   <Employee>
      <empid>1003</empid>
      <name>Steve</name>
      <designation>Web Developer</designation>
      <city>Bangalore</city>
      <country>India</country>
   </Employee>
   <Employee>
      <empid>1004</empid>
      <name>Karthik</name>
      <designation>Business Analyst</designation>
      <city>New Delhi</city>
      <country>India</country>
   </Employee>
   <Employee>
      <empid>1005</empid>
      <name>Chirag</name>
      <designation>Software developer</designation>
      <city>Ahmedabad</city>
      <country>India</country>
   </Employee>
   <Employee>
      <empid>1006</empid>
      <name>Jenish</name>
      <designation>Designer</designation>
      <city>Ahmedabad</city>
      <country>India</country>
   </Employee>
</EmployeeDetails>
Now go to Code behind and Create Method for Retrieve data from SQL table and Call in Page_Load () method so we can Load when Page load First time in browser.

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        BindData();
    }
}

protected void BindData()
{
    DataSet ds = new DataSet();
    try
    {
        ds.ReadXml(Server.MapPath("EmployeeDetails.xml"));
        if (ds != null && ds.HasChanges())
        {
            DataList1.DataSource = ds;
            DataList1.DataBind();
        }
        else
        {
            DataList1.DataBind();
        }
    }
    catch (Exception ex)
    {
    }
}

Now browse you Webpage in browser so we can check XML file called in GridView or Not.
How to encrypt and decrypt xml file in asp.Net

How to encrypt and decrypt xml file in asp.Net

Description:-

In this example we explain that how to encrypt and Decrypt XML file in asp.net with C#.in previous we already explain that how to Encrypt and Decrypt Password when user is register to website then it's password are stored in SqlServer database in Encrypt format and when user is login to website then it will fetch the Encrypt password from the database and Decrypt it and match with user enter password.
So this is simple thing but now in this example we will explain how to encrypt and Decrypt whole XML file in asp.net. The main advantages to Encrypt and Decrypt XML file is that even user cannotsee data in XML file because data are stored in Encrypt format so it cannot be read by any user.
When any operation is performed in XML file then it will first Decrypt XML file and then perform operation. So this is the best facility for any application for better security.

Default.aspx:-

<div>
  <asp:FileUpload ID="flupld_xmlfile" runat="server"/>
  <asp:Button ID="EncryptFileButton" runat="server" Text="Encrypt" onclick="EncryptFileButton_Click"/>
  <asp:Button ID="DecryptFileButton" runat="server" Text="Decrypt" onclick="DecryptFileButton_Click"/>
</div>

Default.aspx.cs:-

protected void Page_Load(object sender, EventArgs e) { }
protected void EncryptFileButton_Click(object sender, EventArgs e)
{
  //Get the Input File Name and Extension. 
  string fileName = Path.GetFileNameWithoutExtension(flupld_xmlfile.PostedFile.FileName);
  string fileExtension = Path.GetExtension(flupld_xmlfile.PostedFile.FileName);
  //Build the File Path for the original (input) and the encrypted (output) file. 
  string input = Server.MapPath("~/Files/") + fileName + fileExtension;
  string output = Server.MapPath("~/Files/") + fileName + "_enc" + fileExtension;
  //Save the Input File, Encrypt it and save the encrypted file in output path. 
  flupld_xmlfile.SaveAs(input);
  this.Encrypt(input, output);
  //Download the Encrypted File. 
  Response.ContentType = flupld_xmlfile.PostedFile.ContentType;
  Response.Clear();
  Response.AppendHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(output));
  Response.WriteFile(output);
  Response.Flush();
  //Delete the original (input) and the encrypted (output) file. 
  File.Delete(input);
  File.Delete(output);
  Response.End();
}

private void Encrypt(stringinputFilePath, stringoutputfilePath)
{
  stringEncryptionKey = "MAKV2SPBNI99212";
  using (Aesencryptor = Aes.Create())
  {
    Rfc2898DeriveBytespdb = newRfc2898DeriveBytes(EncryptionKey, newbyte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
    encryptor.Key = pdb.GetBytes(32); encryptor.IV = pdb.GetBytes(16);
    using (FileStreamfsOutput = newFileStream(outputfilePath, FileMode.Create))
    {
      using (CryptoStreamcs = newCryptoStream(fsOutput, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
      {
        using (FileStreamfsInput = newFileStream(inputFilePath, FileMode.Open))
        {
          int data; while ((data = fsInput.ReadByte()) != -1)
          {
            cs.WriteByte((byte)data);
          }
        }
      }
    }
  }
}

protected void DecryptFileButton_Click(object sender, EventArgs e)
{
  //Get the Input File Name and Extension 
  string fileName = Path.GetFileNameWithoutExtension(flupld_xmlfile.PostedFile.FileName);
  string fileExtension = Path.GetExtension(flupld_xmlfile.PostedFile.FileName);
  //Build the File Path for the original (input) and the decrypted (output) file 
  string input = Server.MapPath("~/Files/") + fileName + fileExtension;
  string output = Server.MapPath("~/Files/") + fileName + "_dec" + fileExtension;
  //Save the Input File, Decrypt it and save the decrypted file in output path. 
  flupld_xmlfile.SaveAs(input);
  this.Decrypt(input, output);
  //Download the Decrypted File. 
  Response.Clear();
  Response.ContentType = flupld_xmlfile.PostedFile.ContentType;
  Response.AppendHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(output));
  Response.WriteFile(output);
  Response.Flush();
  //Delete the original (input) and the decrypted (output) file. 
  File.Delete(input);
  File.Delete(output);
  Response.End();
}

private void Decrypt(stringinputFilePath, stringoutputfilePath)
{
  string EncryptionKey = "MAKV2SPBNI99212";
  using (Aesencryptor = Aes.Create())
  {
    Rfc2898DeriveBytespdb = newRfc2898DeriveBytes(EncryptionKey, newbyte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
    encryptor.Key = pdb.GetBytes(32); encryptor.IV = pdb.GetBytes(16);
    using (FileStreamfsInput = newFileStream(inputFilePath, FileMode.Open))
    {
      using (CryptoStreamcs = newCryptoStream(fsInput, encryptor.CreateDecryptor(), CryptoStreamMode.Read))
      {
        using (FileStreamfsOutput = newFileStream(outputfilePath, FileMode.Create))
        {
          int data; 
          while ((data = cs.ReadByte()) != -1)
          {
            fsOutput.WriteByte((byte)data);
          }
        }
      }
    }
  }
}

fin XmlNode from Xml File in Dynamics ax

fin XmlNode from Xml File in Dynamics ax

Description:-

find XmlNode from Xml File in Dynamics ax Here we will find xml node from XmlDocument. If you want to find single XmlNode that you can find it by using selectSingleNode using XmlDocument class. Here is the example of finding XmlNode from xml file.

Code:-

static void XMLNodeFind(Args _args)
{
    str xml;
    XmlDocument xmlDoc;
    XmlNode xmlNode;
    ;
    xml = @'<ParentNode>
    <Node>
    <Name1>2003</Name1>
    <Name2>20030630</Name2>
    <Name3>20140225</Name3>
    <Name4>46944000</Name4>
    <Name5>94750099</Name5>
    </Node>
    </ParentNode>';
    xmlDoc = XmlDocument::newXml(xml);
    xmlNode = xmlDoc.selectSingleNode('//Name1');
    info(xmlNode.innerText());
}

Read Weater forecast detail in Ax


Description:-

In this article we will see about how to get weather forecast details in dynamics ax. Here i have created sample demo example to read weather forecast data from yahoo and display in ax. Here i have created Job to get data from server and display in ax. When we get data from server then the data will be on Xml format to read data from xml we have to create XElement and read data from xml file and display on ax.

To read data and get data from server i have created demo example to understand easily. Create job and Copy below code to get data from Yahoo server and display it on the Information log in ax.

Code:-

Static void weatherForecast(Args _args)
{
  XmlDocument         doc = new XmlDocument();
  XmlNamespaceManager ns;
  XmlNodeList         nodes,nodes1;
  XmlNode                node,node1;
  //AddressZipCode     addresszipCode;
  container day(str _day)
  {
  ;
    switch(_day)
    {
      case'Mon' : return [1,'Monday'];
      case'Tue' : return [2,'Tuesday'];
      case'Wed' : return [3,'Wednesday'];
      case'Thu' : return [4,'Thursday'];
      case'Fri' : return [5,'Friday'];
      case'Sat' : return [6,'Saturday'];
      case'Sun' : return [7,'Sunday'];
      Default : returnconnull();
    }
  }
  ;
  //addresszipCode = _args.record();
  doc.Load("http://xml.weather.yahoo.com/forecastrss?p=INXX0001&u=c" );// +addresszipCode.ZipCode +’&u=c’);
  // Setup namespace manager for XPath
  ns = new XmlNamespaceManager(doc.nameTable());
  ns.AddNamespace("yweather", "http://xml.weather.yahoo.com/ns/rss/1.0");
  nodes1 = doc.SelectNodes("//rss/channel/item/yweather:condition", ns);
  node1= nodes1.nextNode();
  setprefix("Weather forecast");
  //info(strFmt("%1,Temp : %2,%3", node1.attributes().getNamedItem("date").InnerText(), node1.attributes().getNamedItem("temp").InnerText(), node1.attributes().getNamedItem("text").InnerText()));
  // Getforecast with XPath
  nodes = doc.SelectNodes("//rss/channel/item/yweather:forecast", ns);
  node = nodes.nextNode();
  //setprefix("Weather forecast");
  while(node)
  {
    info("—————————————————–");
    //info(conpeek(day(node.attributes().getNamedItem("day").InnerText()),2));
    //info(node.attributes().getNamedItem("date").InnerText());
    info(strFmt("%1-(%2)", conpeek(day(node.attributes().getNamedItem("day").InnerText()),2), node.attributes().getNamedItem("date").InnerText()));
    info("—————————————————–");
    info( node.attributes().getNamedItem("text").InnerText());
    info('Min :'+node.attributes().getNamedItem("low").InnerText());
    info('Max :'+node.attributes().getNamedItem("high").InnerText());
    if(dayofwk(today()) ==conpeek(day(node.attributes().getNamedItem("day").InnerText()),1))
    {
      info('Current :' +node.attributes().getNamedItem("code").InnerText());
    }
    else
    {
      info('Current : NA');
    }
    node = nodes.nextNode();
  }
}

How to Read and Write Xml File in Dynamics Ax


Description:-

XmlTextWriter Class allows you to Write XML to a file. You can use the inbuilt properties and methods of the XmlTextWriter class to create an xml file. XmlTextWriter Class provides a way to generating a XML Document/File.

1. Create an XmlTextWriter Object.
2. Pass the Xml File name and encoding type parameter through the Object. If encoding parameter is set to Nothing, then default encoding will be "UTF-8".

      XmlTextWriter writer  = new XMlTextWriter("PathtoSaveFile/FileName", null);

3. Indent Xml Document: Use Formatting Property to automatically format the XML File.

      writer.Formatting = Formatting.Indented;

4. Use Following essential Methods as per your requirements.

Write Document

I. WriteStartDocument: This is the very first method of XmlTextWriter object to open new xml document with xml declaration of version 1.0.

      writer.WriteStartDocument();

IIWriteStartElement: This method adds an xml tag inside the xml file. It takes the tag name as a Input.

      writer.WriteStartElement("FirstTagName");     
      It adds the FirstTagName as a tag inside the xml file.

III. WriteStartAttribute: This method adds an attribute to the Created elements. It takes attribute name, xml namespace and prefix string as inputs. We can use xml namespace and prefix string as blank string.

      writer.WriteStartAttribute(" ", "id" " ");     
It adds the attribute 'id' to the student tag.

IV. WriteString: This method writes a text context. This can contain the value of the attribute with xml tag.

      writer.WriteString("1");                 
      It sets the id with the value "1"

V.WriteElementString: Write an element with the specified local name and value.

      writer.WriteElementStrine("Name", "Umesh");          
       It adds the Name tag with value Umesh.

VI.WriteEndAttribute: This method closes the previously added attribute. 

      writer.WriteEndAttribute();        
      It closes the attribute id.

VII. WriteEndElement: It closes one element. If more than one element is present, then it closes the inner one.

      writer.WriteEndElement();          
      It closes the Student tag.

VIII. WriteComments: This method is used to give specific comments while creating the xml file. It takes the Comment string as its input.

      writer.WriteComment("This is the xml file creation using XmlTextWriter");
      This adds the comment in the XML file.

IX. WriteEndDocument: This is the last method which is used to close the Xml document.

      writer.WriteEndDocument();   
      This closes the xml file.

In Dynamic Ax you need to add 

      writer.close();

X. Flush: This method flushes whatever is in the buffer to the underlying streams and also flushes the underlying streams.

      writer.Flush();

Write Xml File Using XmlTextWriter

static void writeXML(Args _args)
{
    XMLTextWriter xw;
    A_PurchaseOrder ObjA_PurchaseOrder;
    str text,filepath;
    container confilter =['.xml','*.xml'];
    ;
    filepath = WinAPI::getSaveFileName(
        0,
        confilter,
        "",
        "Save As",
        "",
        "Untitled");
    xw = XMLTextWriter::new File(filepath);
    xw.writeStartDocument();
    xw.writeStartElement("PurchseOrder");
    while select ObjA_PurchaseOrder
    {
        xw.writeStartElement("Data");
        xw.writeElementString("PurchaseID",ObjA_PurchaseOrder.Purchase_ID);
        xw.writeElementString("VendorCode",ObjA_PurchaseOrder.Vender_Code);
        xw.writeElementString("Status",enum2str(ObjA_PurchaseOrder.Status));
        xw.writeElementString("PurchaseDate",
                date2str(ObjA_PurchaseOrder.Purchase_Date,123,
                DateDay::Digits2,DateSeparator::Hyphen,
                DateMonth::Digits2,DateSeparator::Hyphen,
                DateYear::Digits4));
        xw.writeElementString("PurchaseAmount",int2str(ObjA_PurchaseOrder.Purchase_Amount));
        xw.writeEndElement();
    }
    xw.writeEndElement();
    xw.writeEndDocument();
    xw.close();
}

Read Xml File Using XmlDocument

static void readingXML(Args _args)
{
    str text,filepath;
    containe rconfilter =['.xml','*.xml'];
    XMLDocument xmlDoc;
    inti, nooftags;
    ;
    filepath = WinAPI::getOpenFileName(
        0,
        confilter,
        "",
        "Save As",
        "",
        "Untitled");
    xmlDoc = XMLDocument::newFile(filepath);
    nooftags = xmlDoc.getElementsByTagName("Data").length();
    for(i=0; i<nooftags; i++)
    {
        info(strfmt("%1 | %2 | %3 | %4 | %5",
            xmlDoc.getElementsByTagName("PurchaseID").item(i).text(), 
            xmlDoc.getElementsByTagName("VendorCode").item(i).text(),
            xmlDoc.getElementsByTagName("Status").item(i).text(),
            xmlDoc.getElementsByTagName("PurchaseDate").item(i).text(),
            xmlDoc.getElementsByTagName("PurchaseAmount").item(i).text()));
    }
}

How to Display an XML file to Console in Asp.Net

Description:-


In this article we will Create How to Open Xml File in Console Application. We can use XmlDocument to read an XML document. The Load method is used to load an XML into an XmlDocument. Once a document is loaded, we can use the Save method to display its content to the console. The key is, passing Console.Out as a parameter.

Code:-

static void Main(string[] args)
{
  XmlDocument xmlDoc = new XmlDocument();
  string filename = @"C:\Users\UmesH\Desktop\Customers.xml";
  xmlDoc.Load(filename);
  xmlDoc.Save(Console.Out);
  Console.ReadLine();
}

You must import the using System.Xml namespace in your code. 


How to Read, Edit, Update in XML using Windows Form in Asp.Net


Description:-

In this article we will see Update and Read Operation in Xml File using windows Form. Here we will design form for read record from xml file or if we want to edit record then also we can edit or update record in windows form in Xml file. It’s pretty easy to Read record and Update in Xml file same way we can delete or insert record in xml file. We will do that in next article. Here we will see read and update in xml File.

XML File:-

<?xml version="1.0" standalone="yes" ?>
<Customers>
  <Customer Id="1">
    <Name>Umesh Adroja</Name>
    <Email>Umesh@gmail.com</Email>
    <ZipCode>365420</ZipCode>
    <Country>India</Country>
    <State>Gujrat</State>
    <City>Ahmedabad</City>
  </Customer>
  <Customer Id="2">
    <Name>Chirag Patel</Name>
    <Email>Chirag@gmail.com</Email>
    <ZipCode>235689</ZipCode>
    <Country>India</Country>
    <State>Gujrat</State>
    <City>Rajkot</City>
  </Customer>
</Customers>

For Insert, Update and read Design your Windows form like below.

Now Go to Code behind file to Read, Update in Xml Using Windows Form. And Generate System.Xml Namespace. Create XML Node to Read Xml file from Directory.

int i;
XmlDocument myXMLDoc = new XmlDocument();
XmlNodeList MyName;
XmlNodeList MyEmail;
XmlNodeList MyZipCode;
XmlNodeList MyCountry;
XmlNodeList MyState;
XmlNodeList MyCity;

In Form Load event Read record from Xml file using XmlDocuments and Display in Textboxes.

public Form1()
{
  InitializeComponent();
  myXMLDoc.Load(@"C:\Users\UmesH\Desktop\Customers.xml");

  MyName = myXMLDoc.GetElementsByTagName("Name");
  MyEmail = myXMLDoc.GetElementsByTagName("Email");
  MyZipCode = myXMLDoc.GetElementsByTagName("ZipCode");
  MyCountry = myXMLDoc.GetElementsByTagName("Country");
  MyState = myXMLDoc.GetElementsByTagName("State");
  MyCity = myXMLDoc.GetElementsByTagName("City");

  i = Convert.ToInt16(txtCount.Text);

  txtName.Text = MyName[i - 1].InnerText;
  txtEmail.Text = MyEmail[i - 1].InnerText;
  txtZipCode.Text = MyZipCode[i - 1].InnerText;
  txtCountry.Text = MyCountry[i - 1].InnerText;
  txtState.Text = MyState[i - 1].InnerText;
  txtCity.Text = MyCity[i - 1].InnerText;
}

Now Generate Next button click event to read next record from Xml File like below and display in windows form.

private void btnNext_Click(object sender, EventArgs e)
{
  if (Convert.ToInt16(txtCount.Text) == MyName.Count)
  {
    MessageBox.Show("It's Last Record.", "Info", MessageBoxButtons.OK);
  }
  else
  {
    i = Convert.ToInt16(txtCount.Text);
    i = i + 1;
    txtCount.Text = i.ToString();

    txtName.Text = MyName[i - 1].InnerText;
    txtEmail.Text = MyEmail[i - 1].InnerText;
    txtZipCode.Text = MyZipCode[i - 1].InnerText;
    txtCountry.Text = MyCountry[i - 1].InnerText;
    txtState.Text = MyState[i - 1].InnerText;
    txtCity.Text = MyCity[i - 1].InnerText;
  }
}

Now Generate Previous button click event to read previous record from xml file like below.

private void btnPrevious_Click(object sender, EventArgs e)
{
  if (Convert.ToInt16(txtCount.Text) == 1)
  {
    MessageBox.Show("It's First Record.", "Info", MessageBoxButtons.OK);
  }
  else
  {
    i = Convert.ToInt16(txtCount.Text);
    i = i - 1;
    txtCount.Text = i.ToString();

    txtName.Text = MyName[i - 1].InnerText;
    txtEmail.Text = MyEmail[i - 1].InnerText;
    txtZipCode.Text = MyZipCode[i - 1].InnerText;
    txtCountry.Text = MyCountry[i - 1].InnerText;
    txtState.Text = MyState[i - 1].InnerText;
    txtCity.Text = MyCity[i - 1].InnerText;
  }
}

Now if we want to go first record then generate first button click event and code for go to first record directly.

private void btnFirst_Click(object sender, EventArgs e)
{
  i = 1;
  txtCount.Text = i.ToString();

  txtName.Text = MyName[i - 1].InnerText;
  txtEmail.Text = MyEmail[i - 1].InnerText;
  txtZipCode.Text = MyZipCode[i - 1].InnerText;
  txtCountry.Text = MyCountry[i - 1].InnerText;
  txtState.Text = MyState[i - 1].InnerText;
  txtCity.Text = MyCity[i - 1].InnerText;
}

Now same way to generate last button click event to go directly last record or read last record from xml file.

private void btnLast_Click(object sender, EventArgs e)
{
  i = MyName.Count;
  txtCount.Text = i.ToString();

  txtName.Text = MyName[i - 1].InnerText;
  txtEmail.Text = MyEmail[i - 1].InnerText;
  txtZipCode.Text = MyZipCode[i - 1].InnerText;
  txtCountry.Text = MyCountry[i - 1].InnerText;
  txtState.Text = MyState[i - 1].InnerText;
  txtCity.Text = MyCity[i - 1].InnerText;
}

Now generate Edit button click event to Edit record or enable record in form.

private void btnEdit_Click(object sender, EventArgs e)
{
  btnSave.Visible = true;
  txtName.Enabled = true;
  txtEmail.Enabled = true;
  txtZipCode.Enabled = true;
  txtCountry.Enabled = true;
  txtState.Enabled = true;
  txtCity.Enabled = true;
}

Now Generate Save button click event to save record in xml file and disable display record in windows form like below.

private void btnSave_Click(object sender, EventArgs e)
{
  i = Convert.ToInt16(txtCount.Text);
  MyName[i - 1].InnerText = txtName.Text;
  MyEmail[i - 1].InnerText = txtEmail.Text;
  MyZipCode[i - 1].InnerText = txtZipCode.Text;
  MyCountry[i - 1].InnerText = txtCountry.Text;
  MyState[i - 1].InnerText = txtState.Text;
  MyCity[i - 1].InnerText = txtCity.Text;

  myXMLDoc.Save(@"C:\Users\UmesH\Desktop\Customers.xml");
  if (MessageBox.Show("Save Successfully", "Confirm", MessageBoxButtons.OK) == System.Windows.Forms.DialogResult.OK)
  {
    btnSave.Visible = false;
    txtName.Enabled = false;
    txtEmail.Enabled = false;
    txtZipCode.Enabled = false;
    txtCountry.Enabled = false;
    txtState.Enabled = false;
    txtCity.Enabled = false;
  }
}

Now you are to Read, Edit and Update record in Xml File simply run your Windows form.