Computers And Industry

Receiving and Parsing XML Using Javascript


This code shows a sample of how one can make a request and obtain an xml file. Then, parse the xml elements into variables. This sample requires that the xml file shown below be hosted on a site and requested at the appropriate url.


  John
  Smith
  0024
  2001-01-01T07:00:00
  T
  189.7



Using the Object (Class)


// define global variable
var rq = null;


// -------------------------------
// Do The Web Request
// -------------------------------
function DoRequest()
{

    // get a new request
    var rq = new pfsRq();

    // set the url
    rq.url = "http://sirpenski.local/test/person.xml";

    rq.ahdr("Accept", "text/xml");

    // set the return handler
    rq.responseHandler = DoRequestHandler;

    rq.get();
}


// -------------------------------
// Handle the Web Request Response
// -------------------------------
function DoRequestHandler(rqst)
{
    // see the object below.  the parse utilities
    // are the key to easily and elegantly transforming
    // the xml to values.
    var xUtil = new  pfsXmlParseUtilities();

    var first = "";
    var last = "";
    var id = 0;
    var birthday = new Date(0);
    var is_mean = false;
    var weight = 0;

    if (!rqst.error)
    {
      // get the root elements.  The request class
      // sets xd as the xml document.
      var rootEl = rqst.xd.documentElement;

      // now iterate for each child element
      for (var i = 0; i < rootEl.childNodes.length; i++)
      {

        // if the node is an element, then let's parse it
        if (rootEl.childNodes[i].nodeType == 1)
        {
          // assign just to save some typing.
          var el = rootEl.childNodes[i];

          // get the element value based upon the
          // current element.
          switch(el.nodeName)
          {
            case "FIRST":
              first = xUtil.getElStr(el);
              break;
            case "LAST":
              last = xUtil.getElStr(el);
              break;
            case "ID":
              id = xUtil.getElInt(el);
              break;
            case "BIRTHDAY":
              birthday = XUtil.getElDt(el);
              break;
            case "IS_MEAN":
              is_mean = XUtil.getElBool(el);
              break;
            case "WEIGHT":
              weight = XUtil.getElFloat(el);
              break;
        }

      }

      // build an output message
      var msg = "RESPONSE: " + \n" +
                "First: " + first + "\n" +
                "Last: " + last + "\n" +
                "Id: " + id.toString() + "\n" +
                "Bday: " + birthday.toString() +
                "IsMean: " + is_mean.toString() +
                "Weight: " + weight.toString();

      // display or log to console.
      alert(msg);

    }

    // dispose
    rq = null;

}


The pfsXmlParseUtilities Object (class)

The pfsXmlParsingUtilities class contains a set of functions that aid in parsing the xml document into variables. Refer to the comments to see what each function does. They are very small so they should be easily understandable. Note too that this class makes use of the pfsRq object (class)

// ***************************************************************
// This object provides a set of functions to assist in parsing xml
// ***************************************************************

function pfsXmlParseUtilities()
{

  // ----------------------------------------------------------
  // Gets a string value
  // ----------------------------------------------------------
  this.strToStr = function(s, d)
  {
    var rt = this.defStr(d);
    if (s) {
      rt = s;
    }
    return rt;
  }


  // ----------------------------------------------------------
  // converts string to float
  // ----------------------------------------------------------
  this.strToFloat = function(s, d)
  {

    var r = this.defFloat(d);
    if (s) {
      var tmp = parseFloat(s, 10);
      if (!isNaN(tmp)) {
        r = tmp;
      }
    }
    return r;
  }


  // ----------------------------------------------------------
  // converts string to int
  // ----------------------------------------------------------
  this.strToInt = function(s, d)
  {
    var r = this.defInt(d);
    if (s) {

      var tmp = parseInt(s, 10);
      if (!isNaN(tmp)) {
        r = tmp;
      }
    }
    return r;
  }

  // ---------------------------------------------------------
  // converts string to true/false
  // ---------------------------------------------------------
  this.strToBool = function(s,d)
  {
    var r = this.defBool(d);
    if (s) {
      if (s.length > 0) {
          var tmp = s.substring(0,1).toUpperCase();
          if (tmp == "F") {
          r = false;
          }
        else {
            if (tmp == "T") {
             r = true;
          }
        }
      }
    }

    return r;
   }

  // -----------------------------------------------------------
  // converts string to date using Moment.js.  Handles more 
  // formats
  // -----------------------------------------------------------
  this.strToDtMoment = function(s,d)
  {
        var r = this.defDt(d);

        var dtMoment = moment(s);
        var tmp = dtMoment.toDate();

    if (!isNaN(tmp)) {
      r = tmp;
    }
    return r;
    }


    // ------------------------------------------------------------
    // parses ISO DATE (YYYY-MM-DDTHH:MM:SS)
    // ------------------------------------------------------------
    this.strToDt = function(s, d)
    {
      var r = this.defDt(d);
      var yy = 0;
      var mon = -1;
      var dd = 0;
      var hh = -1;
      var mm = -1;
      var ss = -1;

      // split into date and time.
      var a = s.split('T');

      // do the date portion
      if (a.length > 0)
      {
         // split the date portion
         var b = a[0].split("-");

         // set the year
         if (b.length > 0)
         {
            yy = parseInt(b[0],10);
         }

         // set the month
         if (b.length > 1)
         {

            mon = parseInt(b[1],10);

            // adjust the month for javascript
            mon = mon - 1;
         }

         // set the day;
         if (b.length > 2)
         {
            dd = parseInt(b[2],10);
         }
      }


      // now do the time
      if (a.length > 1)
      {
         var b = a[1].split(":");

         // set the hour
          if (b.length > 0)
          {
             hh = parseInt(b[0],10);
          }

          // set the minute
          if (b.length > 1)
          {
             mm = parseInt(b[1],10);
          }

          // set the second;
          if (b.length > 2)
          {
             ss = parseInt(b[2],10);
          }

      }


      if ((yy > 0) &&
          (mon >= 0 and mon <= 11) &&
          (dd > 0 && dd < 32) &&
          (hh >= 0 && hh <= 23) &&
          (mm >= 0 && mm <= 59) &&
          (ss >= 0 && ss <= 59))
      {
          rt = new Date(yy,mon,dd,hh,mm,ss);
      }

      return rt;
  }





    // ------------------------------------------------------------
    // Converts a string "hh:mm:ss" 24 hour format to date value
    // ------------------------------------------------------------
    this.strToTm = function (s, d)
    {
        var r = this.defTm(d);

        var a = s.split(':');
        if (a.length == 3)
        {
            var hh = parseInt(a[0], 10);
            if (!isNaN(hh)) {
                var mm = parseInt(a[1], 10);
                if (!isNaN(mm)) {
                    var ss = parseInt(a[2], 10);
                    if (!isNaN(ss)) {
                        if (hh >= 0 && hh <= 23) {
                            if (mm >= 0 && mm <= 59) {
                                if (ss >= 0 && ss <= 59) {
                                    r = new Date(0, 0, 0, hh, mm, ss);
                                }
                            }
                        }
                    }
                }
            }
        }
        return r;

    }




    // ------------------------------------------------------------
    // converts a string to money
    // ------------------------------------------------------------

    this.strToMoney = function (s, d)
    {
        var r = this.defFloat().toFixed(2);
        var f = this.strToFloat(s)
        if (!isNaN(f)) {
            r = f.toFixed(2);
        }
        return r;
    }


    this.mfmt = function (v)
    {
        var r = "0.00";
        if (!isNaN(v)) {
            r = v.toFixed(2);
        }
        return r;
    }


  // ------------------------------------------------------------
  // Gets Int Default Value
  // ------------------------------------------------------------
  this.defFloat = function(n)
  {
    var rt = 0;
    if (n != undefined) {
      if (n != null) {
        if (!isNaN(n)) {
          rt = n;
        }
      }
    }
    return rt;
  }

  // ------------------------------------------------------------
  // Gets Default Int Value
  // ------------------------------------------------------------
  this.defInt = function(n)
  {
    var rt = 0;
    if (n != undefined) {
      if (n != null) {
        if (!isNaN(n)) {
          rt = n;
        }
      }
    }
    return rt;
  }

  // ------------------------------------------------------------
  // Gets Default String Value
  // ------------------------------------------------------------
  this.defStr = function(n)
  {
    var rt = "";
    if (n != undefined) {
      if (n != null) {
        rt = n;
      }
    }
    return rt;
    }

    // -------------------------------------------------------------
    // gets a time default
    // -------------------------------------------------------------
    this.defTm = function (tm)
    {
        var rt = this.getZeroDate();
        if (tm != undefined) {
            if (tm != null) {
                if (tm) {
                    rt = tm;
                }
            }
        }
    }


  // -------------------------------------------------------------
  // Gets a booleand default
  // -------------------------------------------------------------
  this.defBool = function(b)
  {
    var rt = false;
    if (b != undefined) {
      if (b != null) {
        if (b) {
          rt = b;
        }
      }
    }
    return rt;
  }


  // -------------------------------------------------------------
  // Gets Default Date
  // -------------------------------------------------------------

  this.defDt = function(dt)
  {
    var rt = null;

    if (dt != undefined) {
      if (dt != null) {
        if (!isNaN(dt)) {
          rt = dt;
        }
      }
    }

    return rt;
  }






    // ---------------------------------------------------------------
    // Converts boolean to T/F
    // ---------------------------------------------------------------

  this.boolToStr = function(b)
  {
      var rt = "F";
      if (b) {
          rt = "T";
      }
      return rt;
  }



    // -----------------------------------------------
    // getTextNode gets the first text child node of
    // the parent node which is an element
    // -----------------------------------------------
  this.getTextNode = function(nd)
  {
      var rt = null;
      var nds = nd.childNodes;
      for (var i = 0; i < nds.length; i++) {
          if (nds[i].nodeType == 3) {
              rt = nds[i];
          }
      }
      return rt;
  }

    // ------------------------------------------------
    // Gets the TExt node value.  returns null if
    // text node not found
    // ------------------------------------------------
  this.getTextNodeValue = function(nd)
  {
      var rt = null;
      var txt = this.getTextNode(nd);
      if (txt != null) {
          rt = txt.nodeValue;
      }
      return rt;
  }

    // -----------------------------------------------
    // Gets element value as an int
    // -----------------------------------------------
  this.getElInt = function(nd)
  {
      var rt = 0;
      var txt = this.getTextNodeValue(nd);
      if (txt != null) {
          rt = this.strToInt(txt);
      }
      return rt;
  }

    // ----------------------------------------------
    // Gets the element value as a float
    // ----------------------------------------------
  this.getElFloat = function(nd)
  {
      var rt = 0;
      var txt = this.getTextNodeValue(nd);
      if (txt != null) {
          rt = this.strToFloat(txt);
      }
      return rt;
  }

    // -----------------------------------------------
    // Gets the Element Value as a string
    // ----------------------------------------------
  this.getElStr = function(nd)
  {
      var rt = "";
      var txt = this.getTextNodeValue(nd);
      if (txt != null) {
          rt = decodeURIComponent(this.strToStr(txt));
      }
      return rt;
  }

    // ----------------------------------------------
    // gets the element value as a date
    // ----------------------------------------------
  this.getElDt = function(nd)
  {
      var rt = null;
      var txt = this.getTextNodeValue(nd);
      if (txt != null) {
          rt = this.strToDt(txt);
      }
      return rt;
    }


    // ----------------------------------------------
    // gets the element value as a date
    // ----------------------------------------------
    this.getElTm = function (nd) {
        var rt = null;
        var txt = this.getTextNodeValue(nd);
        if (txt != null) {
            rt = this.strToTm(txt);
        }
        return rt;
    }

    // ----------------------------------------------
    // Gets the Element Value as a bool
    // ----------------------------------------------
  this.getElBool = function(nd)
  {
      var rt = false;
      var txt = this.getTextNodeValue(nd);
      if (txt != null) {
          rt = this.strToBool(txt);
      }
      return rt;
  }

}  // end class

Open Source

Paul F. Sirpenski
Personal Open Source Directory Of Paul F. Sirpenski

ASP.NET Core
Open Source directory Of the Microsoft Asp.Net Core project.

Developed By Paul F. Sirpenski. Copyright 2021.