ASP.NET
  Home arrow ASP.NET arrow Page 3 - Retrieving and Processing XML with ASP.Net
ASP Free Forums 
.NET  
ASP  
ASP Code  
ASP.NET  
ASP.NET Code  
BrainDump  
C#  
Code Examples  
Database  
Database Code  
IIS  
Microsoft Access  
MS SQL Server  
Visual Basic.NET  
Windows Scripting  
Windows Security  
XML  
ASP Web Hosting  
ASP.NET Web Hosting 
Mobile Linux 
App Generation ROI 
Windows Web Hosting
 
IBM® developerWorks 
Sun Developer Network 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
ASP.NET

Retrieving and Processing XML with ASP.Net
By: Justin Cook
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 5
    2005-07-18

    Table of Contents:
  • Retrieving and Processing XML with ASP.Net
  • The Code and Explanation
  • Using the XML Exchanger

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    Retrieving and Processing XML with ASP.Net - Using the XML Exchanger


    (Page 3 of 3 )

    To provide the most basic of examples on which you can feel free to expand to your heart’s content, let’s assume our client application is simply looking to retrieve information about a person. For this person, we have only the user ID, and we know we can query our remote user database through a web API, that will return all the details in XML format. I’ll step through the code, just as I did with the XMLExchanger class.

    namespace MyXMLProject
    {
      // step 1
      
    using System;
      using System.Web.UI;
      using System.Web.UI.HtmlControls;
      using System.Web.UI.WebControls;
      using System.Xml;

      public class WebForm1 : Page
      {

        // step 2
        protected TextBox EmailTxt;
        protected TextBox FirstNameTxt;
        protected TextBox LastNameTxt;
        protected TextBox CompanyTxt;

        private void Page_Load(object sender, EventArgs e)
        {

          if (!IsPostBack)
          {

            // step 3
            int userID;
            try
            {
              userID = Convert.ToInt16(Request.QueryString["id"]);
            }
            catch (Exception)
            {
              userID = 0;
            }

            // step 4
            LoadDataFromXML(GetXML(userID));
          }
        }

        private XmlTextReader GetXML(int userID)
        
    {
         
    // step 5
         
    XMLExchanger exchange1 = new XMLExchanger();
         
    exchange1.proxy =
            (Request.ServerVariables["SERVER_NAME"].IndexOf("localhost") == -1)
             ? "http://liveproxy:8080" : "http://testproxy";

          // step 6
          XmlTextReader reader1 = null;
         
    try
         
    {
           
    reader1 = exchange1. transmitXML("?userID=" + userID);
         
    }
         
    catch (Exception exception1)
         
    {
           
    // however you want to surface the error
          
    }
         
    return reader1;
       
    }

        // step 7
        
    private void LoadDataFromXML(XmlTextReader xtr)
        {
          while (xtr.Read())
          {
            string text2;
            // step 8
            if (xtr.NodeType != XmlNodeType.Element)
            {
              continue;
            }
            string text1 = xtr.Name.ToLower();
            xtr.Read();
            if (xtr.NodeType == XmlNodeType.Text)
            {
              text2 = xtr.ReadString();
              switch (text1)
              {
                case "email":
                {
                  this.EmailTxt.Text = text2;
                  continue;
                }
                case "firstname":
                {
                  this.FirstNameTxt.Text = text2;
                  continue;
                }
                case "lastname":
                {
                  this.LastNameTxt.Text = text2;
                  continue;
                 }
                 case "company":
                 {
                   this.CompanyTxt.Text = text2;
                   continue;
                }
              }
            }
          }
        }
      }
    }

    Code Explained

    Steps:

    1. Import the namespaces, don’t forget System.Xml!
    2. Declare objects on the ASP.Net page in this case. This will be unnecessary with .Net 2.0 and the advent of partial classes. I’m only reading first and last name, email, and company. You can customize this to your needs.
    3. Here we attempt to pull the user ID out of the query string. If it is not a valid integer value, then you can decide how you want to display an error. For the sake of simplity, I just assigned the value of 0 to move on with the code. You would however opt to prompt the user to input a valid user ID.
    4. Here two steps actually take place on one line. First we call the GetXML method with the ID of the user, which in turn uses our XMLExchanger class. This returns XML, which we pass into the method to load the data into our form fields.
    5. Here’s where we’re actually instantiating the XMLExchanger class, and declaring its properties. There’s a nice line there to switch the proxy depending if you’re running the code in development versus production, therefore you wouldn’t need to manually change the proxy before deploying the application.
    6. Here we call the transmitXML method, passing only the string necessary to get the user info. Therefore the default URL is being used, only the query string parameter is appended. You could even pass through XML in string format here, if that’s what your remote system requires to process a request. An XML reader is returned.
    7. This method steps through the XML, node by node to read the data, and populate the appropriate fields with the pertinent user information. I use ‘while xtr.Read()’ to sequentially read the XML until the end.
    8. Depending on how the data is structured, you may need to modify this to suit your needs. I wanted to read only elements, so I skip everything else. You can set it up to look for attributes, or anything else you need to read.

    XML is a very fast, reliable method of transmitting data. No doubt the methods described in this article will be useful to you, they’ve proven themselves essential in a number of applications I’ve created.


    DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

     

    ASP.NET ARTICLES

    - Advantages of the ASP.NET MVC Approach
    - ASP.NET Web Forms Weaknesses
    - ASP.NET Web Forms Meets ASP.NET MVC
    - Source Code for Saving and Retrieving Data w...
    - Using GridView to Save and Retrieve Data wit...
    - Handling Dynamic Images in ASP.NET 3.5 AJAX ...
    - Retrieving Data with AJAX and the GridView C...
    - Playing with Images in ASP.NET 3.5 AJAX Appl...
    - Saving and Retrieving Data with AJAX
    - Enhancing PHP Via the ASP.NET AJAX Framework...
    - Enhancing PHP Programming with the ASP.NET A...
    - Classes and ASP.NET AJAX
    - Using ASP.NET AJAX
    - Building a Simple Storefront with LINQ
    - Developing a Dice Game Using ASP.NET Futures...





    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 5 hosted by Hostway
    Stay green...Green IT