everyone. I'm practicing dom4j and Xpath but got stuck on a problem.
I'm trying to:
List<Element> conList = (List<Element>)doc.selectNodes("//contact");
but got an Error:
Cannot cast from List<Node> to List<Element>
The code seems to be working fine in a teaching video, but didn't work in my computer.
Is it kind of an illegal operation? Can I solve the problem by any other way? Thanks.
You cannot simply cast a generics based object with concrete parameter that way.
A nice java8 way to achieve your goal is:
List<Element> conList = doc.selectNodes("//contact")
.stream()
.map(node->(Element)node)
.collect(Collectors.toList());
Beware that for a general case in which you dont know if the list elements are actually an instance of your target class or interface, you may would want to assert that by filtering
List<Element> conList = doc.selectNodes("//contact")
.stream()
.filter(node->node instanceof Element)
.map(node->(Element)node)
.collect(Collectors.toList());