Working with XML Files [1]

Windows Application

Form1.cs


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.IO;
namespace pr13
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
System.Windows.Forms.DialogResult OPEN = openFileDialog1.ShowDialog();
if (OPEN == DialogResult.OK)
{
string path = openFileDialog1.FileName; // The Path to the .Xml file //
FileStream READER = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); //Set up the filestream (READER) //
System.Xml.XmlDocument CompSpecs = new System.Xml.XmlDocument();// Set up the XmlDocument (CompSpecs) //
CompSpecs.Load(READER); //Load the data from the file into the XmlDocument (CompSpecs) //
System.Xml.XmlNodeList NodeList = CompSpecs.GetElementsByTagName("CompSpecs"); // Create a list of the nodes in the xml file //
textBox1.Text = NodeList[0].FirstChild.ChildNodes[0].InnerText; // Load Type //
textBox2.Text = NodeList[0].FirstChild.ChildNodes[1].InnerText; // Load RAM //
textBox3.Text = NodeList[0].FirstChild.ChildNodes[2].InnerText; // Load CPU Speed //
}
}
private void button2_Click(object sender, EventArgs e)
{
if (openFileDialog1.FileName.Length > 0) //If a file is open
{
string path = openFileDialog1.FileName; // The Path to the .Xml file //
FileStream READER = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); //Set up the filestream (READER) //
System.Xml.XmlDocument CompSpecs = new System.Xml.XmlDocument();// Set up the XmlDocument (CompSpecs) //
CompSpecs.Load(READER); //Load the data from the file into the XmlDocument (CompSpecs) //
System.Xml.XmlNodeList NodeList = CompSpecs.GetElementsByTagName("CompSpecs"); // Create a list of the nodes in the xml file //
NodeList[0].FirstChild.ChildNodes[0].InnerText = textBox1.Text; // Save the type
NodeList[0].FirstChild.ChildNodes[1].InnerText = textBox2.Text; // Save the RAM
NodeList[0].FirstChild.ChildNodes[2].InnerText = textBox3.Text; // Save the CPU Speed
//Save the xml file
//Create a FileStream for writing
FileStream WRITER = new FileStream(path, FileMode.Open, FileAccess.Write, FileShare.ReadWrite); //Set up the filestream (READER) //
//Write the data to the filestream
CompSpecs.Save(WRITER);
}
}
private void button3_Click(object sender, EventArgs e)
{
Close();
}
}
}

Leave a Reply