Search Forum
(53671 Postings)
Search Site/Articles

Archived Articles
712 Articles

C# Books
C# Consultants
What Is C#?
Download Compiler
Code Archive
Archived Articles
Advertise
Contribute
C# Jobs
Beginners Tutorial
C# Contractors
C# Consulting
Links
C# Manual
Contact Us
Legal

GoDiagram for .NET from Northwoods Software www.nwoods.com


 
Printable Version

Processing XML Documents in C#
By Mesbah U. Ahmed

The major objectives of this article are to demonstrate how to write an XML document from a database query, and subsequently, how to read an XML document using C#? Obviously, we will have to use the ADO.Net to connect to the database. The Dot.Net DataSet class has two convenient methods to read and write XML documents. These are: DataSet.WriteXml(fileStream), and DataSet.ReadXml(fileStream). The WriteXml method generates the XML document including the MS XSD schema at the top.

Files to download:
ReadXML.cs Download
WriteXML.cs Download

1. How to write an XML document from a database query?

The following code will write an XML document named myXMLdata.xml in the directory of the source file. In this example, we want to run a SQL query to the Products table of the SQL Server 7.0 Northwind database, and construct an XML document from the results of the query. At first we need to include two Namespaces: the System.Data for using the ADO.Net classes, and the System.Data.SQL for using the SQL Server managed provider. The System.IO and the System.Text namespaces are used for the FileStream and StringBuilder classes, respectively.

Building the SQL string is a common task in database applications. Since the String objects are immutable (that means, it cannot be copied or modified at the same memory location), a StringBuffer object is more desirable while extending long strings in several steps. Hence, a StringBuilder object has been used to build the SQL string. The remainder of the code is self-explanatory.

// MyDotNet\myCSharp\XML\ WriteXML.cs
// Author: Mesbah U. Ahmed
using System;
using System.Data;// for ADO.Net
using System.Data.SQL;	 // for SQL Server managed provider
using System.IO;	     // for FileStream class
using System.Text;	     // for StringBuilder class
public class WriteXML
{ public static void Main()
  {     // Build a connection
         SQLConnection myConn = 
         new SQLConnection
         ("server=yourServerName;uid=yourUserId;pwd=yourPassword;database=Northwind");
      // Build the SQL string
      StringBuilder mySql = new StringBuilder("SELECT ProductId, ");
      mySql.Append("ProductName, UnitPrice ");
      mySql.Append("FROM Products ");
      mySql.Append("WHERE UnitPrice < 10.00");
      mySql.Append("ORDER BY UnitPrice "); 
      Console.WriteLine(mySql);

      // Build the DataSet Command object
      SQLDataSetCommand myCmd = new SQLDataSetCommand
                                                            (mySql.ToString(), myConn);
       // Build the DataSet     
      DataSet myDs = new DataSet();

      // Fill the DataSet with a dataset table named "Products"
      myCmd.FillDataSet(myDs, "Products");

      // Get a FileStream object
      FileStream myFs = 
          new FileStream
             ("myXmlData.xml",FileMode.OpenOrCreate,FileAccess.Write);

      // Use the WriteXml method of DataSet object to write an XML file from the DataSet
      myDs.WriteXml(myFs);
      myFs.Close();
      Console.WriteLine("File Written");
  }
}
Compilation: While compiling the source code, we will need to reference the System.Data.dll and System.XML,dll assemblies as follows:

csc /r:System.Data.dll;System.XML.dll WriteXML.cs

After the exe file has been run successfully, it will generate the myXmlData.xml file in the directory of the source code. The first part of the XML file will contain the XSD schema, and the second part will contain the XML elements. You may open the XML file using the Notepad, or you may open it in the IE5.5. In IE 5.5 it will appear as follows. A truncated version of the IE screen is shown below.

2.How to read data from an XML document?

The following code will read data from the myXmlData.xml file. Here, a DataSet object is loaded from a FileStream object. Then a DataTable object is created from the DataSet table. Finally, we iterate through each row of the DataTable to display the values.

// MyDotNet\myCSharp\XML\ReadXML.cs
// Author: Mesbah U. Ahmed
using System;
using System.Data;
using System.Data.SQL;
using System.IO;

public class ReadXML
{ public static void Main()
  {   
      // Get a DataSet object
      DataSet myDs = new DataSet();
      
      // Get a FileStream object.
      FileStream myFs = 
          new FileStream
             ("myXmlData.xml",FileMode.Open,FileAccess.Read);
      // Apply the ReadXml(fileSteeam method) to read the file
      myDs.ReadXml(myFs);
      
      // Get a DataTable object from the first table of the DataSet
      DataTable myDt = myDs.Tables[0];
      
      // Display the values for each row
      foreach (DataRow r in myDt.Rows)
         Console.WriteLine("{0} : {1} : ${2:f2}",
             r["ProductId"], r["ProductName"], 
                 Double.Parse(r["UnitPrice"].ToString()));
      myFs.Close();
  }
}
Compilation: While compiling the code, the usage of the DataTable object forces us to refer to the System.dll assembly. We may compile the code as follows:

csc /r:System.Data.dll;System.XML.dll;System.dll ReadXML.cs

When the Exe file is run, it will generate the following console output:

Conclusion: Microsoft has invested on the XML technology extensively. XML provides an excellent way to cross-communicate data from site to site, and most likely it will be the major foundation of B2B systems. It appears that the .Net environment has many utilities, classes and features in the XML domain (mostly without clear documentations). More articles on processing XML documents in C# environment would be of great help.

References:

1.Harvey et al, "C# Programming With Public Beta", Wrox
2.Young, Michael, "XML: Step By Step", Microsoft Press
3.Hunter, David, "Beginning XML", Wrox.