Working with XML Reader and Writer

The System.Xml namespace provides the XmlReader and XmlWriter classes that enable you to parse and write XML data from streams or XML documents.

XMLReader

The XmlReader class allows you to access XML data from a XML document. The XmlTextReader class is used when you require fast access to XML data.

Below is the code to read data from an XML document using XmlTextReader object.

Visual Basic .NET

Dim reader As New XmlTextReader("c:\mysecond.xml")
While reader.Read
Select Case reader.NodeType
Case XmlNodeType.Element
Response.Write("<br>")
Response.Write("&lt;" & reader.Name & "&gt;")
Case XmlNodeType.Text
Response.Write(reader.Value)
Case XmlNodeType.EndElement
Response.Write("&lt;/" & reader.Name & "&gt;")
End Select
End While

Visual C#.Net

XmlTextReader readxml = new XmlTextReader("myfirst.xml");


XMLWriter

The XmlWriter class is an abstract class that enables you to write data to well-formed XML documents. The XmlTextWriter class, which is a derived class of XmlWriter, provides properties and methods that you use to write XML data to a file, stream, console, or other types of output.

Visual Basic .NET

Dim xmlwrite As New XmlTextWriter("c:\mysecond.xml", System.Text.Encoding.UTF8)

xmlwrite.WriteStartElement("Employees")
xmlwrite.WriteStartElement("Employee", Nothing)
xmlwrite.WriteElementString("FirstName", "Bonny")
xmlwrite.WriteElementString("LastName", "M")
xmlwrite.WriteElementString("DOB", "15/07/1948")
xmlwrite.WriteElementString("DOJ", "25/12/1958")
xmlwrite.WriteEndElement()
xmlwrite.WriteEndElement()
xmlwrite.Close()

Visual C#.Net

XmlTextWriter writexml =new XmlTextWriter("c:\mysecond.xml",
System.Text.Encoding.UTF8);

xmlwrite.WriteStartElement("Employees");
xmlwrite.WriteStartElement("Employee", Nothing);
xmlwrite.WriteElementString("FirstName", "Bonny");
xmlwrite.WriteElementString("LastName", "M");
xmlwrite.WriteElementString("DOB", "15/07/1948");
xmlwrite.WriteElementString("DOJ", "25/12/1958");
xmlwrite.WriteEndElement();
xmlwrite.WriteEndElement();
xmlwrite.Close();