TechieClues TechieClues
Updated date Oct 25, 2022
How to Read and Write XML Documents in C#
  • 3.8k
  • 0
  • 0

Download File(s):

ReadWriteXMLDocuments.rar

XML (eXtensible Markup Language ) is a simple text document that stores structured information like documents, data, configuration, transactions, and more.

We can use easily read and write XML documents using C#, The System.xml namespace provides essential support for processing XML, also System.Xml.Schema, System.Xml.Serialization, System.Xml.XPath, and System.Xml.Xsl to support XML classes in C#.

Usually, we use reader and writer classes to read and write the XML documents. Those classes are XmlReader, XmlTextReader, XmlValidatingReader, XmlNodeReader, XmlWriter, and XmlTextWriter

In this article, we will learn how to read and write XML Documents in C#. 

How to Write XML Documents Using C#?

In this example, we are using XmlTextWriter it to write the data to an XML document.

XmlTextWriter provides you to write XML to a file that contains a number of methods and properties that will allow you to perform many operations. 

The class will accept the filename and the encoding parameters to create the XML file. We will use this class properties to add the content to the XML document as shown below,

using System;
using System.Xml;

namespace WriteXmlDocument
{
    class Program
    { 
        static void Main(string[] args)
        {
            using (var writer = new XmlTextWriter("books.xml", System.Text.Encoding.UTF8))
            {
                writer.WriteStartDocument(true);
                writer.Formatting = Formatting.Indented;
                writer.Indentation = 2;
                writer.WriteStartElement("Books");
                AddContent("1", "Drift", "L.T Ryan", "$50.00", writer);
                AddContent("2", "Downburst", "L.T Ryan", "$30.00", writer);
                AddContent("3", "Exiles", "Jane", "$20.00", writer);
                AddContent("4", "12 Rules for Life", "Jordan", "$10.00", writer);
                AddContent("5", "Think Again", "Adam", "$19.00", writer);
                writer.WriteEndElement();
                writer.WriteEndDocument();                
            };
            Console.WriteLine("XML Document is created");
        }

        private static void AddContent(string id, string name, string author, string price, XmlTextWriter writer)
        {
            writer.WriteStartElement("Book");
            writer.WriteStartElement("Id");
            writer.WriteString(id);
            writer.WriteEndElement();
            writer.WriteStartElement("Name");
            writer.WriteString(name);
            writer.WriteEndElement();
            writer.WriteStartElement("Author");
            writer.WriteString(author);
            writer.WriteEndElement();
            writer.WriteStartElement("Price");
            writer.WriteString(price);
            writer.WriteEndElement();
            writer.WriteEndElement();
        }
    }
}

Output:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Books>
  <Book>
    <Id>1</Id>
    <Name>Drift</Name>
    <Author>L.T Ryan</Author>
    <Price>$50.00</Price>
  </Book>
  <Book>
    <Id>2</Id>
    <Name>Downburst</Name>
    <Author>L.T Ryan</Author>
    <Price>$30.00</Price>
  </Book>
  <Book>
    <Id>3</Id>
    <Name>Exiles</Name>
    <Author>Jane</Author>
    <Price>$20.00</Price>
  </Book>
  <Book>
    <Id>4</Id>
    <Name>12 Rules for Life</Name>
    <Author>Jordan</Author>
    <Price>$10.00</Price>
  </Book>
  <Book>
    <Id>5</Id>
    <Name>Think Again</Name>
    <Author>Adam</Author>
    <Price>$19.00</Price>
  </Book>
</Books>

How to Read XML Documents Using C#?

We will use XmlTextReader parse the XML data which contains the attribute names, prefixes, and namespaces as individual String objects when a document is read.

using System;
using System.Xml;

namespace ReadXmlDocument
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var textReader = new XmlTextReader("E:\\books.xml"))
            {
                Console.WriteLine("Books");
                Console.WriteLine("-------------");
                // Read the file
                textReader.Read();
                // Read the line in the file
                while (textReader.Read())
                {                 
                    // Move to fist element
                    textReader.MoveToElement();
                    switch (textReader.Name)
                    {
                        case "Book":
                            Console.WriteLine();
                            break;
                        case "Id":
                            Console.WriteLine("Id: " + textReader.ReadString());
                            break;
                        case "Name":
                            Console.WriteLine("Name: " + textReader.ReadString());
                            break;
                        case "Author":
                            Console.WriteLine("Author: " + textReader.ReadString());
                            break;
                        case "Price":
                            Console.WriteLine("Price: " + textReader.ReadString());
                            break;                       
                    }
                }
                Console.ReadKey();
            }
        }
    }
}

Output:

Books
-------------

Id: 1
Name: Drift
Author: L.T Ryan
Price: $50.00


Id: 2
Name: Downburst
Author: L.T Ryan
Price: $30.00


Id: 3
Name: Exiles
Author: Jane
Price: $20.00


Id: 4
Name: 12 Rules for Life
Author: Jordan
Price: $10.00


Id: 5
Name: Think Again
Author: Adam
Price: $19.00

ABOUT THE AUTHOR

TechieClues
TechieClues

I specialize in creating and sharing insightful content encompassing various programming languages and technologies. My expertise extends to Python, PHP, Java, ... For more detailed information, please check out the user profile

https://www.techieclues.com/profile/techieclues

Comments (0)

There are no comments. Be the first to comment!!!