Reading and Writing XML Files in
C#
Writing XML Files :
Okay lets see how we can write XML files. Writing
and Reading Xml files are most important because sometimes they can also be used
as a database. Lets see how we can write and read xml files.
Typically, you use an XmlTextWriter if you
need to write XML as raw data without the overhead of a DOM. The XmlTextWriter
is an implementation of the XmlWriter class that provides the API which
writes XML to file, stream, or a TextWriter. This class provides numerous
validation and checking rules to ensure that the XML being written is well
formed. When certain violations occur, exceptions are thrown and these
exceptions should be handled. The XmlTextWriter has different
constructors, each of which specifies a different type of the location to which
to write the XML data. This sample uses the constructor that writes XML to a
file. In particular, the following sample code constructs an XmlTextWriter with
a string representing the file location for the newbooks.xml
file.
| XmlTextWriter
myXmlTextWriter = new XmlTextWriter ("newbooks.xml", null); |
C# Code:
myXmlTextWriter.Formatting
= Formatting.Indented;
myXmlTextWriter.WriteStartDocument(false);
myXmlTextWriter.WriteDocType("bookstore", null, "books.dtd",
null);
myXmlTextWriter.WriteComment("This file represents another fragment
of a book store inventory database");
myXmlTextWriter.WriteStartElement("bookstore");
myXmlTextWriter.WriteStartElement("book",
null);
myXmlTextWriter.WriteAttributeString("genre","autobiography");
myXmlTextWriter.WriteAttributeString("publicationdate","1979");
myXmlTextWriter.WriteAttributeString("ISBN","0-7356-0562-9");
myXmlTextWriter.WriteElementString("title", null, "The
Autobiography of Mark Twain");
myXmlTextWriter.WriteStartElement("Author", null);
myXmlTextWriter.WriteElementString("first-name",
"Mark");
myXmlTextWriter.WriteElementString("last-name",
"Twain");
myXmlTextWriter.WriteEndElement();
myXmlTextWriter.WriteElementString("price", "7.99");
myXmlTextWriter.WriteEndElement();
myXmlTextWriter.WriteEndElement();
//Write the XML to file and close the myXmlTextWriter
myXmlTextWriter.Flush();
myXmlTextWriter.Close(); |
In creating this element, the
preceding sample code also shows how, for each XML node type, there is
corresponding XML write method. For example, writing an element calls the WriteElementString
method and writing an attribute calls the WriteAttributeString method.
For nested levels, you use the WriteStartElement / WriteEndElement pair
and, for more complex attribute creation, you can use the WriteStartAttribute
/ WriteEndAttribute pair.
When writing XML, notice how the
sample code writes the XML declaration with the version "1.0" using
the WriteStartDocument method. If you want the writer to check that the
document is well formed (XML declaration first, DOCTYPE in prolog, only
one root level element, and so on), you must call this optional WriteStartDocument
method before calling any other write method. Next, the code calls the WriteDocType
method to writes the document type with the name "bookstore". The
third parameter in the call to the WriteDocType specifies that the writer is to
write SYSTEM "books.dtd". By writing this, the XML file indicates that
there is an external DTD to validate against.
Finally, the sample code calls
the Flush method to persist the XML data to a file before calling the Close
method. (While this sample only really requires the Close method, there are
occasions where the XML generated needs to be persisted and the writer reused.)
To check the output from the
XmlTextWriter, perform a round trip test by reading in the generated file with
an XmlTextReader to validate that the XML is well formed.
Reading Xml Files :
XmlReader class is the API that provides
XML parsing, the XmlTextReader is the implementation designed to handle
byte streams.
Typically, you use the XmlTextReader if you need
to access the XML as raw data without the overhead of a DOM. Not having to
access the DOM results in a faster way to reading XML. For example, an XML
document could have a header section used for routing the document for
processing elsewhere. The XmlTextReader has different constructors to specify
the location of the XML data. This sample loads XML from the books.xml
file, as shown in the following code.
| XmlTextReader
reader = new XmlTextReader ("books.xml"); |
Once loaded, the XmlTextReader moves across the XML data by using the Read method sequentially retrieving the next record from the document. The Read method returns false if there are no more records.
while (reader.Read())
{
// Do some work here on the data
...
} |
To process the XML data, each
record has a node type that can be determined from the NodeType
property. After the NodeType enumeration returns the node type, the
sample tests the node type to see whether it is either an element or document
type. If the node is either one of these two types, the sample processes the
node using the Name and Value properties to display details about the node.
The Name property returns the node name (for instance, the element and
attribute names, while the Value property returns the node value (node text)
of the current node (record).
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element: //
The node is an Element
Console.Write("<" + reader.Name);
while
(reader.MoveToNextAttribute()) // Read attributes
Console.Write(" " + reader.Name + "='" +
reader.Value + "'");
Console.Write(">");
break;
case XmlNodeType.DocumentType:
// The node is a DocumentType
Console.WriteLine(NodeType + "<" + reader.Name +
">" + reader.Value);
break;
...
}
} |
The XmlNodeType returned depends on
the XmlReader class being used. For example, the XmlTextReader class never
returns an XmlNodeType that is a Document, DocumentFragment, Entity, EndEntity
and Notation node. See the .NET Framework Class Library for details on what
XmlNodeType are returned by each XmlReader class.
Read more on Reading
and Writing Text Files and Reading
and Writing Binary Files.
I hope you like the article, happy coding !