perfectxml.com
 Basic Search  Advanced Search   
Topics Resources Free Library Software XML News About Us
home » Info Bank » Articles » XML for C# Programmers [Part I] Saturday, 23 February 2008
 

Back to Articles Page      

        

XML for C# Programmers [Part I]


Table of contents
Introduction
System.Xml Namespace
Writing XML
Reading XML
Summary

  • Introduction
    If you are writing XML applications using Visual Studio 6.0, then using MSXML 4.0 is a great option to work with XML documents. But if you are writing code for the .NET platform, the language of choice is C# (pronounced C Sharp) and XML classes provided by the .NET Framework are the preferred way of manipulating XML data.

    In this article series, we'll look at how .NET Framework supports XML and related standards. First we'll start with simple examples illustrating writing and reading XML documents. Later, in future articles we'll dig more deep into details and do transformation, filtering, database integration, write Web services and more.

    This article assumes you are familier with .NET Framework and C#. Also, you'll need .NET Framework SDK installed to run sample examples presented in this article. Click here External link to download .NET Framework SDK. For future articles, we may also need Visual Studio.NET but for this article, we'll write the code in Notepad and compile using C sharp command line compiler (csc.exe).


  • System.Xml Namespace
    MSXML (or Microsoft XML Core Services), the Microsoft's XML component is a great DOM and SAX Parser, with support for XSLT, XPath, etc. It's very easy to use MSXML in Visual Studio 6.0 applications, but with .NET framework having concept of Managed and Unmanaged code, if you wish to use any COM component, you'll have to use .NET's "Interop Services". To use MSXML (which is also a set of COM components) in .NET, the first step is creating an assembly for MSXML using TLBIMP utility. Next, you need to import the MSXML Namespace and reference the generated assembly at compilation time. This is possibly best approach if you wish to migrate your existing MSXML based code to .NET, with minimal changes. But if you are writing (or can afford to re-write) fresh XML applications, you should surely look at the XML classes provided by .NET framework. The reasons being ease of use and great support to current standards. Performance can be one more reason to use .NET Framework XML classes, because with these classes you can use non-cached forward-only streaming model, rather than in-memory tree (DOM) model, for XML processing.

    The .NET Framework XML classes are made available through various System Namespaces. The core classes are available in System.Xml namespace. There are other namespaces that we'll discuss in coming articles. XmlReader and XMLWriter are the two abstract classes at the core of .NET Framework XML classes. These two classes define the common functionality that all derived classes must support. XmlReader provides a fast, forward-only, read-only cursor for processing an XML document stream. XmlWriter provides an interface for producing XML document streams that conform to the W3C's XML 1.0 and Namespaces Recommendations. So, if you are writing code to read XML documents, use XmlReader, and to create XML documents, use XmlWriter.

    XmlTextReader (a class derived from XmlReader) supports reading XML documents from a text-based stream, while XmlTextWriter (a class derived from XmlWriter) allows writing XML documents to a text-based stream.

    XmlNodeReader (a class derived from XmlReader) supports reading XML documents as in-memory DOM tree , while XmlNodeWriter (a class derived from XmlWriter) allows writing XML documents as in-memory trees.

    This really is a great design work, since in future, implementors can derive classes from XmlReader, XmlWriter and other classes, to extend/override the existing functionality.

    All of the classes discussed above and many other classes (and namespaces) are grouped under System.Xml Namespace, which is assembed as System.Xml.dll. So to use the .NET Framework XML classes in C#, you should import the System.Xml namespace with the help of "using" directive. And while compiling (csc.exe) the code, you'll have to pass "System.Xml.dll" assembly to /r parameter.


  • Writing XML
    Let's now directly jump to the code. In this article also, we'll generate our standard BankAccount XML document.

    Start Notepad and type following lines of C# code:


    namespace WriteXML
    {
        using System;
        using System.Xml;

        public class BankAccount
        {
           private const string m_strFileName = "c:\\account.xml";

           public static void Main()
           //Make sure M is in uppercase in Main() above
           {
              XmlTextWriter bankWriter = null;
              bankWriter = new XmlTextWriter (m_strFileName, null);

              try
              {
                 bankWriter.Formatting = Formatting.Indented;
                 bankWriter.Indentation= 6;
                 bankWriter.Namespaces = false;

                 bankWriter.WriteStartDocument();

                 bankWriter.WriteStartElement("", "BankAccount", "");

                 bankWriter.WriteStartElement("", "Number", "");
                 bankWriter.WriteString("1234");
                 bankWriter.WriteEndElement();

                 bankWriter.WriteStartElement("", "Name", "");
                 bankWriter.WriteString("Darshan Singh");
                 bankWriter.WriteEndElement();

                 bankWriter.WriteStartElement("", "Type", "");
                 bankWriter.WriteString("Checking");
                 bankWriter.WriteEndElement();

                 bankWriter.WriteStartElement("", "OpenDate", "");
                 bankWriter.WriteString("11/04/1974");
                 bankWriter.WriteEndElement();

                 bankWriter.WriteStartElement("", "Balance", "");
                 bankWriter.WriteString("25382.20");
                 bankWriter.WriteEndElement();

                 bankWriter.WriteEndElement();
                 bankWriter.Flush();
              }
              catch(Exception e)
              {
                 Console.WriteLine("Exception: {0}", e.ToString());
              }
              finally
              {
                 if (bankWriter != null)
                 {
                    bankWriter.Close();
                 }
              }
           }
        }
    }



    Save above source code as WriteXML.cs file and to compile above code, type following command on the MS-DOS command prompt:
    csc /r:System.Xml.dll WriteXML.cs
    This will result in WriteXML.exe, run the exe and you should see an XML document file named account.xml created on your c:\ root.

    The above C# code simply uses XmlTextWriter class to create an XML document as a text stream. If you just go through the code line-by-line, it should be easy to understand and obvious. In the next part of the article, we'll look at XmlTextWriter class and it's members in more details. Now let's move forward to reading the XML document.


  • Reading XML
    As discussed earlier, you can use XmlReader (derived classes) to read XML documents. Let's again directly jump to the code and see how you can use these XML classes to read XML documents.

    Launch notepad and key in following C# code:


    namespace ReadXML
    {
        using System;
        using System.Xml;

        public class ReadBankAccount
        {
           private const string m_strFileName = "c:\\account.xml";

           public static void Main()
           {
              XmlTextReader bankReader = null;
              bankReader = new XmlTextReader (m_strFileName);

           while (bankReader.Read())
           {
              if (bankReader.NodeType == XmlNodeType.Element)
                 {
                    if (bankReader.LocalName.Equals("Name"))
                    {
                       Console.Write("{0} has balance of $", bankReader.ReadString());
                    }

                    if (bankReader.LocalName.Equals("Balance"))
                    {
                       Console.WriteLine("{0}", bankReader.ReadString());
                    }
                 }
              }
           }
        }
    }


    Save above code as ReadXML.cs and compile it using following command:
    csc /r:System.Xml.dll ReadXML.cs
    This will result in ReadXML.exe. When you run this EXE file from DOS command prompt, the output should look like:
    Darshan Singh has balance of $25382.20
    (Make sure you've c:\account.xml file created in "Writing XML" section.)

    The above code creates object of type XmlTextReader passing the XML file name as a parameter to the constructor. Next, it simply uses a while loop with a call to Read() method, very similar to how we read text files/streams. Inside the loop, we check if the NodeType is an Element, then we print the Name and Balance node values.


  • Summary
    .NET Framework XML classes really simplify XML Programming, without sacrificing performance. At the same time their design is scalable and extensible. In this series of articles, we'll look at each and every class and write small examples for each. This first article simply illustrated how you can use System.Xml Namespace classes to write and read XML documents. In next few articles, we'll take a closer look at these and other XML classes.


If you have any questions or comments, feel free to contact author of this article, Darshan Singh at darshan@perfectxml.com.

  

Back to Articles Page      

All information on this site is for training only. We do not warrant its correctness or its fitness to be used. The risk of using it remains entirely with the user. 

 

  Contact Us | E-mail Us | Site Guide | About PerfectXML | Advertise ©2004 perfectxml.com. All rights reserved. | Privacy