Hello, it is safe to cast Node returned from selectNodes() or selectSingleNodes() to Element if you are sure that XPath expression returns element(s). Depending on XPath it can return Element, Attribute, Text etc. So if you hope your Xpath returns Elements only, it is safe to cast. If you are not sure, you should check type before cast.
Sincerely Filip Jirsák 2009/5/1 Per Olesen <p...@trifork.com>: > I was wondering. Is it safe to cast Node to Element? I am using the > selectSingleNode method, which gives me a Node instance, but I need an > Element instance, to be able to set CDATA data on the node/element. > > I have seen a lot of code when googling, that simply casts the return > value of selectSingleNode to Element, but is it safe? > > From an example in the dom4j cookbook, I see that selectNodes() > returns an (untyped) List, where each list entry then is casted to > Element, like this: > > XPath xpathSelector = DocumentHelper.createXPath("/people/ > pers...@name='James']"); > List results = xpathSelector.selectNodes(doc); > for ( Iterator iter = result.iterator(); iter.hasNext(); ) { > Element element = (Element) iter.next(); > System.out.println(element.getName(); > } > > Does the same hold for selectSingleNode() ? > > > ------------------------------------------------------------------------------ > Register Now & Save for Velocity, the Web Performance & Operations > Conference from O'Reilly Media. Velocity features a full day of > expert-led, hands-on workshops and two days of sessions from industry > leaders in dedicated Performance & Operations tracks. Use code vel09scf > and Save an extra 15% before 5/3. http://p.sf.net/sfu/velocityconf > _______________________________________________ > dom4j-user mailing list > dom4j-user@lists.sourceforge.net > https://lists.sourceforge.net/lists/listinfo/dom4j-user > ------------------------------------------------------------------------------ Register Now & Save for Velocity, the Web Performance & Operations Conference from O'Reilly Media. Velocity features a full day of expert-led, hands-on workshops and two days of sessions from industry leaders in dedicated Performance & Operations tracks. Use code vel09scf and Save an extra 15% before 5/3. http://p.sf.net/sfu/velocityconf _______________________________________________ dom4j-user mailing list dom4j-user@lists.sourceforge.net https://lists.sourceforge.net/lists/listinfo/dom4j-user