Thursday 29 November 2012

JavaScript & XML: validate an XML document

   


I think we all know how to use XML documents. For example RSS feeds are basically XML files, as well as sitemaps. Those files may be very important when managing a web site, but those examples are just a small part of the common use of XML documents. Just to make things clear, another example: when you export a Blogger blog, the file you get is an XML file.
When I've written the article on how to create an RSS feed, I discovered a very useful JavaScript snippet that helps us to validate an XML file.
Unfortunately I don't remember where I got it, but, even if I surely rearranged it, if you know the original source, please let me know so that I can give due credit to the author.
Ok, said that, let's see how to do it.
The code
First of all, let's create a form like the following:
<form name="form1">
  <input type="file" name="file" size="50">
  <input type="button" value="Validate" onclick="Validate()">
</form>
In the input element, we need to insert a valid path to an XML file (it can be local or remote, it doesn't matter).
Then we have a button which will trigger the Validate() function:
<script type="text/javascript">
 function Validate()
{
    var file = document.form1.file.value;

    // create an array in order to check the correct .xml extension in file
    var arr_file = file.split(".");
    var ext = arr_file[arr_file.length - 1]

    // check if file is not empty - if not alert the user
    if (file == "" || file == "undefined" || file.charAt(0) == " ")
    {
        alert("Please insert a file to check");
    }
    // check the file extension (.xml) - if not alert the user
    else if (ext != "xml")
    {
        alert("The submitted file is not an XML file");
    }
    // if everything is ok, then
    else
    {
        // create an XMLDOM
        var x = new ActiveXObject("Microsoft.XMLDOM");

        // load the submitted file
        x.async = false;
        x.load(file);

        // set the XML parser to true
        x.validateOnParse = true;

        // check if there are errors
        var errore = x.parseError.errorCode;

        // if everything's ok, alert the user
        if (errore == 0)
        {
            res.innerHTML = "No error found";
        }
        // if errors were found
        else
        {
            // collect error information
            var err_n = x.parseError.errorCode;
            var err_d = x.parseError.reason;
            var err_r = x.parseError.line;

            // show the errors to the user
            with (res)
            {
                innerHTML  = "Error number " + err_n + "<br>";
                innerHTML += " - " + err_d + "<br>";
                innerHTML += "line " + err_r + "<br>";
            }
        }
        // close the parser
        x.Close();
    }
}
</script>
I decided to leave the comments in the code itself, so it will be easier to understand what it is actually doing.
Now, you may wonder what res is.  Well, it's quite easy: we use a HTML element to show the results of the validation process. So somewhere on the page we need to insert the following:
<div id="res"></div>
That's the place where the results will appear.

Let me know what you think.

2 comments:

  1. Thanks for sharing this with us.

    ReplyDelete
  2. ActiveXObject is only supported in IE. Can you provide me with alternate solutions for both Firefox and Chrome ?

    ReplyDelete

Comments are moderated. I apologize if I don't publish comments immediately.

However, I do answer to all the comments.