0% found this document useful (0 votes)
13 views

Unit-4

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Unit-4

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 5

Working with XML

Extensible Markup Language (XML) is a markup language that defines a set of


rules for encoding documents in a format that is both human-readable and
machine-readable. XML is often used for application configuration, data storage
and exchange. XML is similar to HTML, but does not have predefined tags, we
can design our own tags. The XmlDocument represents an XML document. It
can be used to load, modify, validate, a navigate XML documents. The
XmlDocument class is an in-memory representation of an XML document.
The Document Object Model (DOM) is a language-independent programming
interface for HTML and XML documents. It represents a page. Through the
DOM interface, the programs can change the document structure, style, and
content. The DOM represents the document as nodes and objects. The
XmlElement is a common node in the XmlDocument.XPath (XML Path
Language) is a query language for selecting nodes from an XML document. It
can be also used to compute values from the content of an XML document.
Creating an XML File: -
Before we start reading and writing XML files in C#, we need to create an XML
file that we can work with. We can create an XML file using any text editor,
such as Notepad or Visual Studio Code. An XML file typically consists of a
header, a root element, and child elements. The root element is the top-level
element in the XML file, and all other elements are nested within it. Here is an
example of a simple XML file:
book.xml
<?xml version="1.0" encoding="UTF-8"?>
<books>
<book>
<title>Programming C#</title>
<author>John Doe</author>
<publisher>O'Reilly</publisher>
<price>29.99</price>
</book>
<book>
<title>Database Design</title>
<author>Jane Doe</author>
<publisher>Wiley</publisher>
<price>39.99</price>
</book>
</books>
Reading an XML File in C#:-
Now that we have an XML file to work with, let's explore how to read its
contents using C#. C# provides several ways to read XML files, including using
the XmlDocument and XmlReader classes.

Using the XmlDocument Class: -


The XmlDocument class is part of the System.Xml namespace and provides a
convenient way to read and manipulate XML documents. We can use the Load
method of the XmlDocument class to load an XML file into memory, and then
use the SelectNodes method to retrieve specific elements from the XML file.

using System; using


System.Xml; class
Program
{
static void Main(string[] args)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("books.xml");
XmlNodeList bookNodes = xmlDoc.SelectNodes("//book");
foreach (XmlNode bookNode in bookNodes)
{
string title = bookNode.SelectSingleNode("title").InnerText;
string author = bookNode.SelectSingleNode("author").InnerText;
string publisher = bookNode.SelectSingleNode("publisher").InnerText;
double price =
Convert.ToDouble(bookNode.SelectSingleNode("price").InnerText);

Console.WriteLine("Title: {0}", title);


Console.WriteLine("Author: {0}", author);
Console.WriteLine("Publisher: {0}", publisher);
Console.WriteLine("Price: {0:C}", price);
}
}
}
Using the XmlReader Class:-
The XmlReader class is another way to read XML files in C#. It is a fast and
efficient way to read large XML files because it only reads one element at a
time, rather than loading the entire file into memory.
using System; using
System.Xml; class
Program
{
static void Main(string[] args)
{
using (XmlReader reader = XmlReader.Create("books.xml"))
{
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element && reader.Name ==
"book")
{
string title = reader.GetAttribute("title");
string author = reader.GetAttribute("author");
string publisher = reader.GetAttribute("publisher");
double price = Convert.ToDouble(reader.GetAttribute("price"));

Console.WriteLine("Title: {0}", title);


Console.WriteLine("Author: {0}", author);
Console.WriteLine("Publisher: {0}", publisher);
Console.WriteLine("Price: {0:C}", price);
}
}
}
}
}

Writing an XML File in C#: -


Now that we know how to read XML files in C#, let's explore how to write
XML files. C# provides several ways to write XML files, including using the
XmlDocument and XmlWriter classes.
Using the XmlDocument Class:-
We can use the XmlDocument class to create a new XML document and then
use its various methods to add elements and attributes to the document. Once
we have created the XML document, we can save it to a file using the Save
method.
using System; using
System.Xml; class
Program
{
static void Main(string[] args)
{
XmlDocument xmlDoc = new XmlDocument();

XmlNode booksNode = xmlDoc.CreateElement("books");


xmlDoc.AppendChild(booksNode);

XmlNode bookNode = xmlDoc.CreateElement("book");


booksNode.AppendChild(bookNode);

XmlAttribute titleAttribute = xmlDoc.CreateAttribute("title");


titleAttribute.Value = "Programming C#";
bookNode.Attributes.Append(titleAttribute);

XmlAttribute authorAttribute = xmlDoc.CreateAttribute("author");


authorAttribute.Value = "John Doe";
bookNode.Attributes.Append(authorAttribute);

XmlAttribute publisherAttribute = xmlDoc.CreateAttribute("publisher");


publisherAttribute.Value = "O'Reilly";
bookNode.Attributes.Append(publisherAttribute);

XmlAttribute priceAttribute = xmlDoc.CreateAttribute("price");


priceAttribute.Value = "29.99";
bookNode.Attributes.Append(priceAttribute);

xmlDoc.Save("newbooks.xml");
}
}
Using the XmlWriter Class:
The XmlWriter class is another way to write XML files in C#. It provides a
more efficient way to create large XML files because it writes the XML data
directly to a file, rather than creating an entire XML document in memory.
using System; using
System.Xml; class
Program
{
static void Main(string[] args)
{
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
using (XmlWriter writer = XmlWriter.Create("newbooks.xml", settings))
{
writer.WriteStartElement("books");
writer.WriteStartElement("book");
writer.WriteAttributeString("title", "Programming C#");
writer.WriteAttributeString("author", "John Doe");
writer.WriteAttributeString("publisher", "O'Reilly");
writer.WriteAttributeString("price", "29.99");
writer.WriteEndElement(); writer.WriteEndElement();
}
}
}

In this example, we create an instance of the XmlWriter class and pass the
name of the XML file and an XmlWriterSettings object to the Create method.
We then use the WriteStartElement method to create the "books" element and
the WriteAttributeString method to create the attributes for the "book"
element. Finally, we use the WriteEndElement method to close the "book" and
"books" elements.

You might also like