为什么成员函数返回的值为null?
我写了一个class:
//XMLResource.java
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
public class XMLResource{
private DocumentBuilderFactory dbf;
private DocumentBuilder db;
private Document doc;
private Element root;
private NodeList cmdInforLst;
private int iAppNum =0;
public XMLResource() throws Exception {
dbf = DocumentBuilderFactory.newInstance();
try{
db = dbf.newDocumentBuilder();
doc = db.newDocument();
}catch(Exception e){
throw new Exception(e.getMessage());
}
root = doc.createElement("xmlres");
doc.appendChild(root);
}
// Add item named sitemName as the first child of root.
public XMLResource addItemFirst(String sitemName, String sItemValue){
Node firstItem = null;
Element elItem = doc.createElement(sitemName);
NodeList nodelst = root.getChildNodes();
if(nodelst.getLength() > 0){
firstItem = nodelst.item(0);
root.insertBefore(elItem, firstItem);
}else{
root.appendChild(elItem);
}
Text txtValue = doc.createTextNode(sitemName);
elItem.appendChild(txtValue);
return this;
}
//set root.
public void setRoot(Element root){
this.root = root;
}
//get root.
public Element getRoot(){
return this.root;
}
//Convert XMLResource to string.
public String toString(){
return doc.toString();
}
}
//---------------------------------------------
在Eclipse中跟踪发现,当调用public XMLResource addItemFirst(String sitemName, String sItemValue)完后,会显示它的返回值有[document:null]的信息,然后再调用XMLResource 的toString()将doc转化为String后也为null.不明白这个类哪里不对,为什么doc会为null?