Working with XML

I l @ ve RuBoard

Microsoft has recognized that XML "is the future." XML is becoming a substrate upon which all kinds of solutions are built. It's a great technology for business-to-business (B2B) and application-to-application (A2A) communication. It's useful for persisting data and "Save As" scenarios. It's even being used for platform and language-independent remote procedure calls (see the chapter on Web Services). But, at its core , XML is just text (see Listing 4.28).

Listing 4.28 A customer as XML.
 <?xml version="1.0" encoding="utf-8" ?> <Customer>     <Name>         <First>Scott</First>         <Last>Swigart</Last>     </Name>     <Street>2222 NE Somewhere</Street>     <City>Portland</City>     <State>OR</State>     <ZIP>97211</ZIP>     <Web>http://www.3leafsolutions.com</Web> </Customer> 

Generating XML

The beauty of XML is that you can use it to represent any data, no matter how complex. XML has been used to describe molecules, financial transactions, mathematical equations, vector graphics, purchase orders, Shakespeare's plays, and more. With XML, you are completely free to make up whatever tags you want, and place them in whatever hierarchy you want.

A common use for XML is exporting data from a database so that it can be used on any platform, from any language (see Listings 4.29 and 4.30). Again, ASP.NET makes this simple. You can see the output of this page in Figure 4.7.

Figure 4.7. Converting data to XML.

Listing 4.29 Outputting data as XML ”ExportXML.aspx.
 <%@ Page language="c#"     Codebehind="ExportXML.cs"     AutoEventWireup="false"     Inherits="ado_net_by_example.ExportXML" %> 
Listing 4.30 Outputting data as XML ”ExportXML.cs.
 namespace ado_net_by_example {     using System;     using System.Collections;     using System.ComponentModel;     using System.Data;     using System.Data.SqlClient;     using System.Drawing;     using System.Web;     using System.Web.SessionState;     using System.Web.UI;     using System.Web.UI.WebControls;     using System.Web.UI.HtmlControls;     using System.Xml;     using System.IO;     /// <summary>     ///    Summary description for ExportXML.     /// </summary>     public class ExportXML : System.Web.UI.Page     {     public ExportXML()     {         Page.Init += new System.EventHandler(Page_Init);         }         protected void Page_Load(object sender, EventArgs e)         {             if (!IsPostBack)             {  SqlConnection cn = new SqlConnection(   "server=localhost;" +   "database=pubs;" +   "uid=sa;" +   "password=");   SqlDataAdapter cmd = new SqlDataAdapter(   "select * from authors order by au_lname",cn);   DataSet ds = new DataSet();   cmd.Fill(ds,"authors");   Response.ContentType="text/xml";   StringWriter s = new StringWriter();   ds.WriteXml(s);   Response.Write (s.ToString());  }         }         protected void Page_Init(object sender, EventArgs e)         {             //             // CODEGEN: This call is required by the ASP+ Windows Form Designer.             //             InitializeComponent();         }         /// <summary>         ///    Required method for Designer support - do not modify         ///    the contents of this method with the code editor.         /// </summary>         private void InitializeComponent()         {             this.Load += new System.EventHandler (this.Page_Load);         }     } } 

As you can see, the DataSet contains a method called WriteXml that takes a Stream as an argument. This way, we can easily write XML out to a text file, or store it in a string. In our case, we simply output the string with Response.Write , and now we've exposed data from our database to the Internet as XML.

If we want to generate a Schema to go with our XML data, it's also very simple:

 Response.ContentType="text/xml"; StringWriter s = new StringWriter(); ds.WriteXmlSchema(s); Response.Write (s.ToString()); 

This outputs to the following:

 <xsd:schema id="NewDataSet" targetNamespace="" xmlns=""     xmlns:xsd="http://www.w3.org/2001/XMLSchema"     xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"> <xsd:element name="NewDataSet" msdata:IsDataSet="true">   <xsd:complexType>     <xsd:choice maxOccurs="unbounded">       <xsd:element name="authors">         <xsd:complexType>           <xsd:sequence>             <xsd:element name="au_id" type="xsd:string" minOccurs="0" />             <xsd:element name="au_lname" type="xsd:string" minOccurs="0" />             <xsd:element name="au_fname" type="xsd:string" minOccurs="0" />             <xsd:element name="phone" type="xsd:string" minOccurs="0" />             <xsd:element name="address" type="xsd:string" minOccurs="0" />             <xsd:element name="city" type="xsd:string" minOccurs="0" />             <xsd:element name="state" type="xsd:string" minOccurs="0" />             <xsd:element name="zip" type="xsd:string" minOccurs="0" />             <xsd:element name="contract" type="xsd:boolean" minOccurs="0" />           </xsd:sequence>         </xsd:complexType>       </xsd:element>     </xsd:choice>   </xsd:complexType> </xsd:element> </xsd:schema> 

If you've done much work with XML, you may notice that this schema looks a little different than what you're used to. The Microsoft XML Parser (MSXML) supported a schema specification called "XML Data Reduced (XDR)," which was essentially Microsoft-specific. In the meantime, the W3C has been working on an industry-standard schema recommendation. I'm happy to report that .NET supports the W3C recommendation. What's even better is that a DataSet can generate this schema document for you just by calling its WriteXmlSchema method.

Consuming XML

Fortunately, XML isn't a one-way trip for a DataSet . A DataSet can populate itself just as easily from an XML document (see Listing 4.31).

Listing 4.31 Populating a DataSet from XML.
 DataSet ds = new DataSet(); ds.ReadXmlSchema(Server.MapPath("AuthorSchema.xsd")); ds.ReadXml(Server.MapPath("Authors.xml")); DataGrid1.DataSource = ds.Tables["authors"].DefaultView; DataGrid1.DataBind(); 

To populate a DataSet , we just create an instance of a DataSet object. If we have a schema, we load it first by calling the ReadXmlSchema method of the DataSet . This needs a physical path to the file, so we use Server.MapPath to convert the relative path to the physical path.

After we've read in the schema, the DataSet knows the columns, and the data types of the columns . We can now load in the actual data with a call to ReadXml . That's it! Our DataSet is populated , and we can bind a DataGrid to it as before.

I l @ ve RuBoard


Asp. Net. By Example
ASP.NET by Example
ISBN: 0789725622
EAN: 2147483647
Year: 2001
Pages: 154

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net