C# School Assignment? Project Due Tomorrow? Chat LIVE With A Programming Expert!

Welcome to Dream.In.Code
Become a C# Expert!

Join 300,442 C# Programmers for FREE! Get instant access to thousands of C# experts, tutorials, code snippets, and more! There are 1,519 people online right now. Registration is fast and FREE... Join Now!




Working with XML files in C#

 
Reply to this topicStart new topic

> Working with XML files in C#

aj32
Group Icon



post 12 Apr, 2008 - 07:55 PM
Post #1


Working With XML Files in C#



This is a basic tutorial which will show you how to write a C# program to work with XML files, we will be using the .NET module System.Xml.


For this tutorial, we will pretend we have been hired to create a program that will read xml files with specifications of your emplorer's computers. The XML files are structured like this:
xml

<?xml version="1.0"?>
<CompSpecs>
<CP>
<Type>Dell Dimension 6600</Type>
<RAM>2GBs</RAM>
<CPU_Speed>2.8Ghz</CPU_Speed>
</CP>
</CompSpecs>



To start, create a C# windows Forms Application, and create a form as shown below:

IPB Image

*Note: by default, the three textboxes should be named textBox1, textBox2, textBox3.

As you can see, we will load three items for each computer, Type, Amount of RAM, and the CPU Speed.
Now add an "open file dialog" to our project, to allow the user to open a "computer specifications xml file".

To get started, we will set up the loading part of our program, go into code view of Form1.h, and add the following using references:
csharp

using System.Xml;
using System.IO;


Reading and parsing xml content

To read and parse the xml file, we will:
  1. Create a file stream
  2. Create an XmlDocument that will read the filestream
  3. Parse the XmlDocument
  4. Display the InnerText of the Nodes with the needed information in it
First, go back into design mode, and double-click the "Load" Button, to create an onclick() event. In the newly created event, insert this code:

csharp

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 //
}


We can now run our program and click the "Load" Button, the program should then load the above mentioned xml file, and output the data like this:

IPB Image



Now, that was simple enough wasn't it!


Changing and saving xml content

We will now need to create the Save function of our program. To edit and save the xml contents, we will:
  1. Open a filestream
  2. Load the contents of the filestream into an XmlDocument
  3. Parse the XmlDocument
  4. Edit the InnerText of the nodes that are being edited
  5. Save the xmlDocument
To do this, create an "onClick()" event for our "Save" Button, and type in the code below in the newly created function:

csharp

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);
}


There we have it, the above code will allow us to change the xml file's attributes to match the ones the user has entered!


This is the end of this tutorial, I hope it was useful to you! Thanks for reading!
- AJ32 smile.gif

I have finished writing part two of this XML tutorial: Working with xml files in C# - Part 2 smile.gif

This post has been edited by aj32: 16 Apr, 2008 - 05:58 PM
Go to the top of the page
+Quote Post


Register to Make This Ad Go Away!

jousian
*



post 8 May, 2009 - 04:53 AM
Post #2
hi ,

I have tried to understand your code ,it's easy but I have a small problem in understanding this line

QUOTE(aj32 @ 12 Apr, 2008 - 07:55 PM) *

Now add an "open file dialog" to our project, to allow the user to open a "computer specifications xml file".


can you explain it more furthur, please ?

Need your answer quickly beacuse I need a very similar code in a project that I will deliver to my teachers in a week

thank you
Go to the top of the page
+Quote Post

Bocard
**



post 12 May, 2009 - 09:06 AM
Post #3
QUOTE(jousian @ 8 May, 2009 - 01:53 PM) *

hi ,

I have tried to understand your code ,it's easy but I have a small problem in understanding this line

QUOTE(aj32 @ 12 Apr, 2008 - 07:55 PM) *

Now add an "open file dialog" to our project, to allow the user to open a "computer specifications xml file".


can you explain it more furthur, please ?

Need your answer quickly beacuse I need a very similar code in a project that I will deliver to my teachers in a week

thank you


you just drag an open file dialog control from the toolbox onto your form
Go to the top of the page
+Quote Post

jousian
*



post 15 May, 2009 - 02:46 AM
Post #4
I want to know how to read several nodes in an Xml file

like this example :

<?xml version="1.0"?>
<CompSpecs>
<CP1>
<Type>Dell Dimension 6600</Type>
<RAM>2GBs</RAM>
<CPU_Speed>2.8Ghz</CPU_Speed>
</CP1>
<CP2>
<Type>Dell Dimension 6600</Type>
<RAM>2GBs</RAM>
<CPU_Speed>2.8Ghz</CPU_Speed>
</CP2>
</CompSpecs>

I knew about the (Nextsibling) method , it means the node beside the fisrt node

" NodeList[0].FirstChild.Nextsibling.ChildNodes[0].InnerText; " .. this line will get me the type in the cp2

but I don't want that .. I want to llop the file to get all the nodes of it without previously knowing how many nodes in the file

how could I do this ?

please help me quickly , me exams is two days to come .


Go to the top of the page
+Quote Post

Kuggi
Group Icon



post 10 Jul, 2009 - 03:00 AM
Post #5
QUOTE
To get started, we will set up the loading part of our program, go into code view of Form1.h, and add the following using references:


Hmm, Form1.h should be Form1.cs in C#.

But, nice short and clear tutorial.
Go to the top of the page
+Quote Post

prashant_kerkar
*



post 17 Jul, 2009 - 09:56 AM
Post #6
I want to save changes i am making to xml file ....plz help






using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;

namespace TestRad
{
public partial class Form8 : Form
{
private XmlDocument xmlDoc;

public Form8()
{
InitializeComponent();
}

private void Form8_Load(object sender, EventArgs e)
{
xmlDoc = new XmlDocument();
LoadDocument();



}


private void LoadDocument()
{
try
{
// Load the XML data into it.
xmlDoc.Load("hosts.xml");

// Initialize the TreeView control.
tvTree.Nodes.Clear();
tvTree.Nodes.Add(new TreeNode(xmlDoc.DocumentElement.Name));
TreeNode tNode = new TreeNode();
tNode = tvTree.Nodes[0];

// Populate the TreeView with the DOM nodes.
AddNode(xmlDoc.DocumentElement, tNode);
tvTree.ExpandAll();
}
catch (XmlException xmlEx)
{
MessageBox.Show(xmlEx.Message);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

private void AddNode(XmlNode xmlNode, TreeNode treeNode)
{
XmlNode xNode;
TreeNode tNode;
XmlNodeList xNodeList;
int i;

// Loop through the XML nodes until the leaf is reached.
// Add the nodes to the TreeView during the looping process.
if (xmlNode.HasChildNodes)
{
xNodeList = xmlNode.ChildNodes;
for (i = 0; i <= xNodeList.Count - 1; i++)
{
xNode = xmlNode.ChildNodes[i];
TreeNode newNode = new TreeNode(xNode.Name);


treeNode.Nodes.Add(newNode);
tNode = treeNode.Nodes[i];

AddNode(xNode, tNode);


}
}
else
{
// Here you need to pull the data from the XmlNode based on the
// type of node, whether attribute values are required, and so forth.
treeNode.Text = (xmlNode.OuterXml).Trim();
}
}

private void tvTree_AfterSelect(object sender, TreeViewEventArgs e)
{
//=e.Node.n
if (e.Node.Nodes.Count == 0)
textBox1.Text = e.Node.Text;
else
textBox1.Text = "";


}

private void btnSave_Click(object sender, EventArgs e)
{
tvTree.SelectedNode.Text = textBox1.Text;
tvTree.Refresh();

//TODO: Traverse the tree recursively and write the nodes to XML file; and reload the document

//LoadDocument(); //remove comment from this to reload the document....
}
}
}
Go to the top of the page
+Quote Post

dccub83
*



post 12 Aug, 2009 - 06:26 AM
Post #7
QUOTE(aj32 @ 12 Apr, 2008 - 07:55 PM) *

csharp

CompSpecs.Load(READER); //Load the data from the file into the XmlDocument (CompSpecs) //



Hey, this is a great little tutorial, exactly what I was looking for to help build an XML reader for a couple of Adobe forms that I've made in my office. The only trouble is with that particular line of code quoted above: it is giving me an error. it occurs once I test run the program, I'll click load and get the dialog box. I'll double-click my xml file and the following is the error it gives me:

XmlException was unhandled.
Data at the root level is invalid. Line 8, position 13.

If it helps, I'm using Microsoft Visual C# 2008 Express Edition. I'm also looking elsewhere for solutions, but as this is literally my first programming experience, I'm having trouble finding anything useful.
Go to the top of the page
+Quote Post

StickyTape
*



post 16 Oct, 2009 - 01:03 AM
Post #8
Superb uncluttered explanation.

It would be nice if you would add some code that adds a child element to a given element.

Thanks for an great explanation

Go to the top of the page
+Quote Post


Fast ReplyReply to this topicStart new topic
1 User(s) are reading this topic (1 Guests and 0 Anonymous Users)
0 Members:

 


Lo-Fi Version Time is now: 11/8/09 01:25AM

Live C# Help!

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter Fan Us On Facebook

C# Tutorials

Reference Sheets

C# Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month