Project

Profile

Help

Casting Nodeset to Nodelist

Added by Anonymous over 16 years ago

Legacy ID: #4710068 Legacy Poster: Spencer Tickner (yea420)

Hi List, Thanks in advance for the help. I'm doing some java work for the first time in a long time and needed an XSLT 2.0 processor so got Saxon9. Since I was using saxon for transformations thought I might as well use it for XPath as well. The problem is the rest of the program relies on Nodelist. According to the java samples and some online searching it seems that I "should" be able to cast a Nodeset to a NodeList, however I am getting errors. Any help would be appreciated. public static void main(String[] args) throws Exception { String sXml = "<?xml version=&quot;1.0&quot;?>" + "<root><test id=&quot;1&quot;>Test</test>" + "<test id=&quot;1&quot;>Other Test</test></root>"; StringBuffer sb = new StringBuffer(sXml); ByteArrayInputStream bis = new ByteArrayInputStream(sXml.toString().getBytes()); System.out.println(Saxon.getStringResults("//test[@id = '" + 1 + "']", bis)[0]); } public static NodeList getNodeResults(String sXPath, ByteArrayInputStream xml) throws XPathFactoryConfigurationException, Exception { System.setProperty("javax.xml.xpath.XPathFactory:http://java.sun.com/jaxp/xpath/dom", "net.sf.saxon.xpath.XPathFactoryImpl"); XPathFactory xpf = XPathFactory.newInstance(NamespaceConstant.OBJECT_MODEL_SAXON); XPath xpe = xpf.newXPath(); InputSource is = new InputSource(xml); SAXSource s = new SAXSource(is); NodeInfo doc = ((XPathEvaluator)xpe).setSource(s); XPathExpression xPath = xpe.compile(sXPath); NodeList nodes = null; try { nodes = (NodeList)xPath.evaluate(doc, XPathConstants.NODESET); } catch (Exception e) { e.printStackTrace(); } return nodes; } Error happens at the line: nodes = (NodeList)xPath.evaluate(doc, XPathConstants.NODESET); StackTrace: java.lang.ClassCastException: java.util.ArrayList cannot be cast to org.w3c.dom.NodeList at reconsearcher.util.Saxon.getNodeResults(Saxon.java:85) at reconsearcher.util.Saxon.getStringResults(Saxon.java:95) at reconsearcher.util.Saxon.main(Saxon.java:51) Exception in thread "main" java.lang.NullPointerException at reconsearcher.util.Saxon.main(Saxon.java:51) Any thoughts on where I'm going wrong? Thanks, Spencer


Replies (1)

RE: Casting Nodeset to Nodelist - Added by Anonymous over 16 years ago

Legacy ID: #4710729 Legacy Poster: Michael Kay (mhkay)

The NodeList class is DOM-specific. If you supply a DOM node as input, and request a NODE_SET as the result type, then it will come back as a NodeList containing DOM nodes. If your input uses any other object model (Saxon, JDOM, DOM4J, XOM) then the result is returned as a plain Java List. Note that Saxon is significantly slower when running against a DOM than when running against the native Saxon tree model.

    (1-1/1)

    Please register to reply