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  
Silverlight  
Visual Basic.NET  
Windows Scripting  
Windows Security  
XML  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
ASP Web Hosting  
ASP.NET Web Hosting 
Windows Web Hosting
 
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

    - Develop Your First ASP.NET Website with Visu...
    - Run ASP.NET in Windows XP Home with Cassini ...
    - How to Test a Web Application
    - How to Add Code and Validation Controls to a...
    - Working in Source and Split Views to Build a...
    - How to Build a Web Form for a One-Page Web A...
    - How to Develop a One-Page Web Application
    - An ASP.NET Web Application in Action
    - Developing ASP.NET Web Applications
    - An Introduction to ASP.NET Web Programming
    - Introduction to the ADO.NET Entity Framework...
    - Completing an In-Text Advertising System und...
    - Programming an In-Text Advertising System un...
    - Building an In-Text Advertising System Under...
    - Developing a Mini ASP.NET AJAX Server Centri...





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 2 Hosted by Hostway
    Stay green...Green IT