Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo
- - - - -

C# Tutorial: Reading and Writing XML Files

xmlreader xml xml files

  • This topic is locked This topic is locked
9 replies to this topic

#1 rueleonheart

rueleonheart

    CC Newcomer

  • Just Joined
  • PipPip
  • 11 posts

Posted 12 August 2010 - 11:53 PM

This tutorial assumes that you already know the basics of XML as I will start directly to coding. To create or manipulate XML files, you must use the classes and methods inside the System.XML namespace of the .NET Framework.

Writing XML Files
We can use the XmlWriter class to write XML files. It allows you to write XML text into a stream and then save it into an xml file.



using System.Xml;

public class Program
{
public static void Main()
{
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;

XmlWriter writer = XmlWriter.Create("Products.xml", settings);
writer.WriteStartDocument();
writer.WriteComment("This file is generated by the program.");
writer.WriteStartElement("Product");
writer.WriteAttributeString("ID", "001");
writer.WriteAttributeString("Name", "Soap");
writer.WriteElementString("Price", "10.00");
writer.WriteStartElement("OtherDetails");
writer.WriteElementString("BrandName", "X Soap");
writer.WriteElementString("Manufacturer", "X Company");
writer.WriteEndElement();
writer.WriteEndDocument();

writer.Flush();
writer.Close();
}
}
 

 

We first import the System.Xml namespace. We use the XmlWriterSettings class to create a setting for the XmlWriter that we will use. We dictated the program to use proper indention when writing the xml by using this settings. We then create an XmlWriter object by calling the XmlWriter.Create method and supplying the filename and the XmlWriterSettings object.


Using the XmlWriter class, we can write our xml. We first use the XmlWriter.WriteStartDocument() method which writes the xml declaration you find on the top of most xml files. Next we create a sample comment using teh XmlWriter.WriteComment() method. To write an Xml Element, we use the XmlWriter.WriteStartElement() and supply the name of the element as the argument. The XmlWriter.WriteStartElement() must be paired with XmlWriter.WriteEndElement which writes the closing tag of that element. We now create some attributes for the element using the XmlWriter.WriteAttributeString() method and supply the name and the value for that attribute.
We used the XmlWriter.WriteElementString() method with a name and a value as the arguments to write an element that is wrapping a value. We then nested another element inside the Products element by writing one more set of XmlWriter.WriteStartElement() and XmlWriter.WriteEndElement() . Inside it, we add two more elements that contain values. To mark the end of the document, we simly call the XmlWriter.WriteEndDocument() method.

Finally, we used the XmlWriter.Flush() method to clean the contents of the stream and the XmlWriter.Close() method to save the file and stop the program from using it.

The above code will produce the following XML file contents:



 

<?xml version="1.0" encoding="utf-8"?>
<!--This file is generated by the program.-->
<Product ID="001" Name="Soap">
<Price>10.00</Price>
<OtherDetails>
<BrandName>X Soap</BrandName>
<Manufacturer>X Company</Manufacturer>
</OtherDetails>
</Product>
 

 


Reading XML Files
To read xml files, we can use the XmlReader class. We will use the XML file we created earlier to assign the values into variables. Note that we will simply use variables for storing the values from the XML. A better approach is by creating a Products class the follows the heirarchy of the XML file. The following program demonstrates the use of XmlReader class.




 

using System;
using System.Xml;

public class Program
{
public static void Main()
{
XmlReader reader = XmlReader.Create("Products.xml");

while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element
&& reader.Name == "Product")
{
Console.WriteLine("ID = " + reader.GetAttribute(0));
Console.WriteLine("Name = " + reader.GetAttribute(1));

while (reader.NodeType != XmlNodeType.EndElement)
{
reader.Read();
if (reader.Name == "Price")
{
while (reader.NodeType != XmlNodeType.EndElement)
{
reader.Read();
if (reader.NodeType == XmlNodeType.Text)
{
Console.WriteLine("Price = {0:C}", Double.Parse(reader.Value));
}
}

reader.Read();

} //end if

if (reader.Name == "OtherDetails")
{
while (reader.NodeType != XmlNodeType.EndElement)
{
reader.Read();
if (reader.Name == "BrandName")
{
while (reader.NodeType != XmlNodeType.EndElement)
{
reader.Read();
if (reader.NodeType == XmlNodeType.Text)
{
Console.WriteLine("Brand Name = " + reader.Value);
}
}
reader.Read();
} //end if

if (reader.Name == "Manufacturer")
{
while (reader.NodeType != XmlNodeType.EndElement)
{
reader.Read();
if (reader.NodeType == XmlNodeType.Text)
{
Console.WriteLine("Manufacturer = " + reader.Value);
}
}

} //end if
}
} //end if
} //end while
} //end if

} //end while
}
}

 

 


Output:

 

ID = 001
Name = Soap
Price = $10.00
Brand Name = X Soap
Manufacturer = X Company
 

 


There are other ways to read Xml files but this tutorial will focus on using the XmlReader class. First, we create an XmlReader object using the static method Create and passing the filename of the XML file that will be read.

 

XmlReader reader = XmlReader.Create("Products.xml");
 

 


We now enter a loop that will read each node in the xml file including the whitespaces. We use the XmlReader.Read() that returns true if there are more nodes to read or false if there is no more or if it reaches the end of the file.

We first look at the Product element. The first condition checks if the current node read by the reader is an element and has a name of "Product". The XmlNodeTpe enumeration list all the possible node types including whitespaces, text and comments. We then show the values of the attributes of the product element:
 

 

Console.WriteLine("ID = " + reader.GetAttribute(0));
Console.WriteLine("Name = " + reader.GetAttribute(1));
 

 


The GetAttribute() method gets the values of the attribute of an element. The number indicates what attribute you are getting. 0 indicates the first attribute and 1 indicates the second attribute.

You will now encounter a series of nested while and if statements. The first while loop will search for the Price element. The Read() method will go to the next node while it is not an end element. If the type of the node is a text, we display it on the screen.

Basically, reading xml files using XmlReader requires you to look carefully at the structure of your XML.

 

Looking for more tutorials on reading and writing files? Check our the below tutorials:

Reading and writing files using File methods

C# Tutorial: Writing Text Files

Visual Studio 2008: C# Reading Files

 

 


Edited by Roger, 24 February 2013 - 10:24 PM.
add links

  • 0

#2 Parabola

Parabola

    CC Addict

  • Just Joined
  • PipPipPipPipPip
  • 221 posts

Posted 30 December 2010 - 07:24 AM

Thank you for this. I'm currently writing an app to help me manage my RDP clients / sessions, and this would be great for helping me store a list of RDP connections for one click connecting, with the ability to add new connections within the program. Trying to stay clear of hard coding any connections....
  • 0
Programmer (n): An organism that can turn caffeine into code.
Programming would be so much easier without all the users.

#3 Parabola

Parabola

    CC Addict

  • Just Joined
  • PipPipPipPipPip
  • 221 posts

Posted 30 December 2010 - 08:44 AM

Thanks again for the point in the right direction!
Here's what I've come up with as far as reading an XML, based on what you had. BTW, I tend to split things up into functions if I can....

First off, XML creation (slightly modified, for more elements):
XmlWriterSettings settings = new XmlWriterSettings();
                settings.Indent = true;

                XmlWriter writer = XmlWriter.Create("settings.xml", settings);
                writer.WriteStartDocument();
                writer.WriteComment("File generated by RDP Manager");
                writer.WriteStartElement("RDP");
                writer.WriteStartElement("Machines");
                
                writer.WriteAttributeString("ID", "0");
                writer.WriteAttributeString("Type", "Sequencing");

                writer.WriteElementString("Name", "ftwsqncws01");
                writer.WriteElementString("Name", "ftwsqncws02");
                writer.WriteElementString("Name", "ftwsqncws03");
                writer.WriteElementString("Name", "ftwsqncws04");
                
                writer.WriteEndElement();
                
                writer.WriteStartElement("Servers");

                writer.WriteAttributeString("ID", "1");
                writer.WriteAttributeString("Type", "Print");

                writer.WriteElementString("Name", "ftwprn04");
                writer.WriteElementString("Name", "ftwprn06");
                writer.WriteElementString("Name", "phdprn04");
                writer.WriteElementString("Name", "phdprn06");
                writer.WriteEndElement();
                writer.WriteEndDocument();

                writer.Flush();
                writer.Close();

Now reading it:
XmlReader reader = XmlReader.Create("settings.xml");


            int n = 0;
            while (reader.Read())
            {
                if ((reader.NodeType == XmlNodeType.Element) && reader.Name != "RDP") //&& reader.Name == "Machines" && reader.GetAttribute(0) == "001")
                {
                    n = Int32.Parse( reader.GetAttribute(0));
                    if (treeRDP.Nodes.Count == n)
                        treeRDP.SelectedNode = treeRDP.Nodes.Add(reader.GetAttribute(1) + " " + reader.Name.ToString());
                    else
                        treeRDP.SelectedNode = treeRDP.Nodes[n];

                    GetNames(reader, n);
                }
            }

GetNames function:
void GetNames(XmlReader reader, int n)
        {
            while (reader.NodeType != XmlNodeType.EndElement)
            {
                reader.Read();
                if (reader.Name == "Name")
                {
                    while (reader.NodeType != XmlNodeType.EndElement)
                    {
                        reader.Read();
                        if (reader.NodeType == XmlNodeType.Text)
                        {
                            treeRDP.SelectedNode = treeRDP.SelectedNode.Nodes.Add(reader.Value.ToString());
                            treeRDP.SelectedNode.ContextMenuStrip = contextMenuStrip1;
                            treeRDP.SelectedNode = treeRDP.Nodes[n];
                        }
                    }
                    reader.Read();
                }
            }
        }

  • 0
Programmer (n): An organism that can turn caffeine into code.
Programming would be so much easier without all the users.

#4 HobbyistCoder

HobbyistCoder

    CC Lurker

  • Just Joined
  • Pip
  • 2 posts

Posted 19 July 2011 - 11:02 AM

I have been reading a lot on working with XML lately and also Data Tables. I'd like to be able to populate a Data Table with the info read from an XML file. I am currently working on my data structure in the XML, what would be the best way to write my data into the Data Table? Via Columns or Rows?

Ex:
<column>
  <row>Value1</row>
  <row>Value2</row>
  <row>Value3</row>
</column>
<column>
  <row>Value4</row>
  <row>Value5</row>
  <row>Value6</row>
</column>

Would this work properly? I am in need of a table about 17x17 with the top row and left column with Labels. Then the left over 16x16 would be Data that I would need to be able to manipulate change etc. Also would need to be able to save the DataTable as XML. I have my file save and open functions working.

I'm just very new to working with XML and Data Tables and now I'm trying to combine them.

Any tips and or tutorials you could link to would be helpful.


And Rep for a tutorial of something that is useful to me.
  • 0

#5 xperia

xperia

    CC Newcomer

  • Member
  • PipPip
  • 10 posts
  • Learning:Java, C#, PHP, JavaScript, PL/SQL

Posted 01 March 2013 - 03:59 AM

Thank you! this will really help me doing my work for school


  • 0

#6 GeverLances

GeverLances

    CC Lurker

  • Just Joined
  • Pip
  • 1 posts

Posted 14 January 2014 - 11:39 PM

Check this tutorial

 

http://csharp.net-in...xmltutorial.htm

 

c# connecting to excel in somany ways details about xml serialization also.

 

Gever


  • 0

#7 mohitparihar22

mohitparihar22

    CC Lurker

  • Just Joined
  • Pip
  • 1 posts

Posted 16 July 2014 - 09:59 PM

hi,

   its nice tutorial and work fine. i have a problem how to

   modify or edit value of specific filed like.

  

  <?xml version="1.0" encoding="utf-8"?>

<!--This file is generated by the program.-->
<Product ID="001" Name="Soap">
<Price>10.00</Price>
<OtherDetails>
<BrandName>X Soap</BrandName>
<Manufacturer>X Company</Manufacturer>
</OtherDetails>
</Product>

 

in this xml how to change or replace the value of Price...? 

please help me asap. thanks.


  • 0

#8 charlesdavis

charlesdavis

    CC Regular

  • Member
  • PipPipPip
  • 34 posts
  • Location:Noida
  • Programming Language:C, C++, C#, PHP, PL/SQL, Visual Basic .NET
  • Learning:Assembly, Fortran, Prolog

Posted 04 May 2015 - 10:42 PM

As I know you don't need to more experience on XML..It is very simple scripting language..You only need to work hard on another suporting language like .net frame work and C# etc.


  • 0

#9 WingedPanther73

WingedPanther73

    A spammer's worst nightmare

  • Moderator
  • 17757 posts
  • Location:Upstate, South Carolina
  • Programming Language:C, C++, PL/SQL, Delphi/Object Pascal, Pascal, Transact-SQL, Others
  • Learning:Java, C#, PHP, JavaScript, Lisp, Fortran, Haskell, Others

Posted 05 May 2015 - 04:20 AM

hi,

   its nice tutorial and work fine. i have a problem how to

   modify or edit value of specific filed like.

  

  <?xml version="1.0" encoding="utf-8"?>

<!--This file is generated by the program.-->
<Product ID="001" Name="Soap">
<Price>10.00</Price>
<OtherDetails>
<BrandName>X Soap</BrandName>
<Manufacturer>X Company</Manufacturer>
</OtherDetails>
</Product>

 

in this xml how to change or replace the value of Price...? 

please help me asap. thanks.

How do you change it with WHAT?

What language are you using to modify the file?


  • 0

Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog

My MineCraft server site: http://banishedwings.enjin.com/


#10 lespauled

lespauled

    CC Leader

  • Expert Member
  • PipPipPipPipPipPipPip
  • 1360 posts
  • Programming Language:C, C++, C#, JavaScript, PL/SQL, Delphi/Object Pascal, Visual Basic .NET, Pascal, Transact-SQL, Bash

Posted 05 May 2015 - 10:33 AM

2014 called, they want this thread to stay dormant  :-P


  • 0
My Blog: http://forum.codecal...699-blog-77241/
"Women and Music: I'm always amazed by other people's choices." - David Lee Roth