HOW TO: Use the XPathException Class in Visual C# .NET (318547)



The information in this article applies to:

  • Microsoft Visual Studio .NET (2003), Enterprise Architect Edition
  • Microsoft Visual Studio .NET (2003), Enterprise Developer Edition
  • Microsoft Visual Studio .NET (2003), Academic Edition
  • Microsoft Visual Studio .NET (2002), Professional Edition
  • Microsoft Visual Studio .NET (2002), Enterprise Architect Edition
  • Microsoft Visual Studio .NET (2002), Enterprise Developer Edition
  • Microsoft Visual Studio .NET (2002), Academic Edition
  • Microsoft XML Classes (included with the .NET Framework 1.1)
  • Microsoft XML Classes (included with the .NET Framework 1.0)

This article was previously published under Q318547
For a Microsoft Visual Basic .NET version of this article, see 317108.

IN THIS TASK

SUMMARY

This step-by-step article demonstrates how to write exception handling code to trap and handle an XPathException (System.Xml.XPath.XPathException). Writing error handling code to catch an XPathException when executing the Select and Compile methods of the XPathNavigator object will help to identify exceptions caused by an invalid XPath query expression.

back to the top

Create the XML Document

  1. Use Notepad to create a new XML document that contains the following code:
    <?xml version='1.0'?>
    <Books>
    <Book>
      <Title>Beginning XML</Title>
      <Publisher>Wrox</Publisher>
    </Book>
    <Book>
      <Title>XML Step by Step</Title>
      <Publisher>MSPress</Publisher>
    </Book>
    <Book>
      <Title>Professional XML</Title>
      <Publisher>Wrox</Publisher>
    </Book>
    <Book>
      <Title>Developing XML solutions</Title>
      <Publisher>MSPress</Publisher>
    </Book>
    </Books>
    					
  2. Save the document as "C:\books.xml".
back to the top

Create the Visual C# .NET Application

  1. Create a new Visual C# .NET Windows Application project.
  2. Drag a command button control from the toolbox to the designer surface of Form1.cs.
  3. Paste the following code in the Click event procedure of the command button:
    try
          {
                //Construct the XPathDocument by specifying the path to books.xml.
                System.Xml.XPath.XPathDocument xmldoc = new System.Xml.XPath.XPathDocument("c:\\books.xml");
    
                //Create the XPathNavigator.
                System.Xml.XPath.XPathNavigator nav = xmldoc.CreateNavigator();
    
                System.Xml.XPath.XPathNodeIterator iterator;
    
                //Error handling code to catch an XPathException that could be generated when an 
                //invalid XPath query expression is specified in the call to the Select method
                //of the XPathNavigator.
    
                try 
                      {
                            //Create the XPathNodeIterator by executing the Select method of the XPathNavigator.
                            iterator = nav.Select("//Publisher[. = 'MSPress']/parent:node()/Title");
                      }
                catch (System.Xml.XPath.XPathException XPathExp)
                      {
                            //Catch the XPathException and write it to the Visual Studio .NET output window.
                            System.Diagnostics.Debug.WriteLine("XPathException:");
                            System.Diagnostics.Debug.WriteLine("***************");
                            System.Diagnostics.Debug.WriteLine(XPathExp.ToString());
                            return;
                      }
    			      
                //Proceed to process results if no XPathException is raised.
                System.Diagnostics.Debug.WriteLine("Titles published by MSPress...");
                System.Diagnostics.Debug.WriteLine("******************************");
    
                //Use the iterator to navigate the generated resultset.
                while (iterator.MoveNext())
                      {
                            System.Diagnostics.Debug.WriteLine(iterator.Current.Value);
    					 }
                      }
    catch (System.Exception otherExp)
          {
                //Error handling code to catch other exceptions.
                System.Diagnostics.Debug.WriteLine("Other Exception:");
                System.Diagnostics.Debug.WriteLine("****************");
                System.Diagnostics.Debug.WriteLine(otherExp.ToString());
                return;
          }
    					
  4. Read the inline comments to understand the functionality of the code. Pay particular attention to the try...catch exception handling code that encapsulates the call to the Select method of the XPathNavigator object. Note that this code is written to specifically catch an XPathException that could be raised when an invalid XPath expression is supplied as the query expression parameter of the Select method. The XPath query expression specified in the above sample is invalid. The axis parent and the node test node() should be separated by a double colon (::) instead of a single colon (:)
  5. Also note the usage of the higher-level generic try...catch exception handling code to trap and handle other exceptions that could be raised by statements other than the call to the Select method of the XPathNavigator object. For instance, modifying the path to the source XML file to specify the name of a nonexistent file would raise a System.IO.FileNotFoundException exception which would be handled by this code. This example is written to catch an instance of the generic System.Exception Class. You could write additional catch blocks to handle other specific .NET exceptions or your own custom exceptions as required by your application.
back to the top

Test the Code

  1. Save the changes to the Visual C# .NET project and then run it.
  2. When the form is displayed, click the command button to execute the code. The following output generated by the error handling code in the catch block to trap an XPathException is displayed in the Visual Studio .NET Output window:
    XPathException:
    ***************
    System.Xml.XPath.XPathException: '//Publisher[. = 'MSPress']/parent:node()/Title' has an invalid token.
       at System.Xml.XPath.XPathParser.ParseXPathExpresion(String xpathExpresion)
       at System.Xml.XPath.QueryBuilder.Build(String query, Boolean allowVar, Boolean allowKey)
       at System.Xml.XPath.QueryBuilder.Build(String query, Boolean& hasPrefix)
       at System.Xml.XPath.XPathNavigator.Compile(String xpath)
       at System.Xml.XPath.XPathNavigator.Select(String xpath)
       at Q318547.Form1.button1_Click(Object sender, EventArgs e) in <path of VC#.NET form>:line <line number>
    					
back to the top

REFERENCES

For additional information, click the article number below to view the article in the Microsoft Knowledge Base:

313828 INFO: Roadmap for Executing XPath Queries in .NET Applications


Modification Type:MinorLast Reviewed:5/23/2005
Keywords:kbHOWTOmaster KB318547 kbAudDeveloper