Friday, 13 May 2011

SAXBuilder ClassNotFoundException When Creating a SAX Parser.

I was recently using JDom to parse some XML.

      InputStream is = new FileInputStream(fileName);

      SAXBuilder builder =
new SAXBuilder();
      retVal = builder.build
(is);

Everything was pretty straight forward untill the code ran, when the build() method threw a ClassNotFoundException and started asking me for a missing Weblogic class. So I added it to my classpath and ran the code again and the same thing happened only now a different class was missing. Now this was surprising as I wasn’t using Weblogic, I was using Tomcat!

I’m guessing that one of my super poms specifies the class somewhere or other and it got built into my WAR file, but that’s not the point. It turns out that the SAXBuilder uses the first SAX parser it finds on the classpath, which in my case was a Weblogic one. In order to fix this problem, you need to specify the SAX Driver class by using an alternative constructor.

      InputStream is = new FileInputStream(fileName);

      SAXBuilder builder =
new SAXBuilder("org.apache.xerces.parsers.SAXParser");
      retVal = builder.build
(is);

By specifying the driver class, the SAXBuilder will use the class you want it to use rather than some random class it just happens to find somewhere.

No comments: