Implementing Error Handling with XSLT and the DOM


This topic adds error handling functionality to the script in the previous topic, Using XSLT with the DOM from an HTML Page.

XSLT does not provide a native error-detecting and error-reporting mechanism for determining whether a transformation works as intended, or for handling exceptions when they occur. To implement error-handling while processing XSLT or XML, use the following DOM facilities:

  • Set the validateOnParse property of a DOMDocument object. When this property is set to "false" before the object is loaded, the parser checks to see if the document is well-formed. When set to "true", the parser validates the XML document against a DTD or its XML Schema definitions.

  • After an XSLT style sheet (or any other XML file) is loaded, check the errorCode property of the parseError object (that is, xmldom.parseError.errorCode, where xmldom is a DOM instance of the XML document). If the value of this property is "0", the document was parsed without error. Any other value indicates that an error has occurred. To examine the nature of the error, check other properties of the parseError object. For example, the xmldom.parseError.reason property describes the cause of the error, and xmldom.parseError.line indicates where the error occurred. For more information, see IXMLDOMParseError Members, in XML DOM Reference.

To validate the region.xsl style sheet, add the following JScript fragments to the transformIt() function within the HTML file, qsalesregion.html. For more information about the files for this example, see Using XSLT with the DOM from an HTML Page.

To add the following code to the transformIt() function

  1. Insert the following line immediately after the declaration of the objXSLT object variable.

    objXSLT.validateOnParse = true;

  2. Insert the following lines of Jscript code immediately after the objXSLT.load('region.xsl') statement.

    if (objXSLT.parseError.errorCode != 0)   
      var strErrMsg = "Problem Parsing Style Sheet:<br />"  
       + "  Error #: "             + objXSLT.parseError.errorCode + "<br />"  
       + "  Description: "         + objXSLT.parseError.reason + "<br />"  
       + "  In file: "             + objXSLT.parseError.url + "<br />"  
       + "  Line #: "              + objXSLT.parseError.line + "<br />"  
       + "  Character # in line: " + objXSLT.parseError.linepos + "<br />"  
       + "  Character # in file: " + objXSLT.parseError.filepos + "<br />"  
       + "  Source line: "         + objXSLT.parseError.srcText;  
      objResTree.innerHTML = strErrMsg;  
      return false;  

The resulting file is shown in XSLT HTML DOM File with Error Handling.

Similar logic for validating the XML document, region.xml, could be provided at analogous locations in the script.

Performing Error Handling with XSLT