Dom4j: error "incompatible types" on compilation
I am developing a small desktop application in Java. I came across a point where i need to read data from XML file, for this i am using Dom4j library. While coding i am facing the following error could anyone guide me in resolving this error:
public void FromXML(String sXMLFileURI)
{//Reads the XML File and Stroe Data in Calling Object
Document document = getDocument( sXMLFileURI );
String xPath = "myXpath";
List<Node> nodes = document.selectNodes( xPath );//This line gives the followiing error:
//error "incompatible types
//required: java.util.List<org.dom4j.Node>
//found: java.util.List<capt开发者_StackOverflow中文版ure#1 of ? extends org.dom4j.Node>"
for (Node node : nodes)
{
//some processing here
}
}
It's a consequence of the fact that java generic collections are not "covariant". Method selectNodes() returns a list of Objects all of which implement Node. But this is not a List<Node>
. You have to change the declaration to
List<? extends Node> nodes=...
Since the method signature is
List<? extends Node> selectNodes(String)
your variable nodes
should be of type List<? extends Node>
, and not of type List<Node>
.
A List<Node>
accepts any Node
instance as element. Whereas a List<? extends Node>
is a List<Node>
, or a List<Element>
, or a List<Attribute>
, or a list of some other subclass of Node
. You just don't know which one.
精彩评论