为什么成员函数返回的值为null?

WiseNeuro 2006-07-26 11:16:49
我写了一个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?
...全文
301 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
UnAgain 2006-07-27
  • 打赏
  • 举报
回复
DOM处理部分是正确的,Node是接口,其实现类没有实现toString()方法,需要自己写。下面仅举一例。

public String toString(){
String s="";

NodeList nodelst = root.getChildNodes();

for (int i=0; i<nodelst.getLength(); i++) {
s += nodelst.item(i).getNodeName() + "\n";
}

return s;
}

另外,
Text txtValue = doc.createTextNode(sitemName);
中的sitemName应该是笔误吧
WiseNeuro 2006-07-27
  • 打赏
  • 举报
回复
谢谢UnAgain().你说的是对的.原来org.w3c.dom.Document就是接口类。这样的话就需要自己实现它了。要遍历所有节点,而且需要保证与原来的xml结构相同,是不是采用深度优先遍历较好构造,也就是说,如果发现一个节点,就一直查找它的子节点并转为string拼接,直到它没有子节点时再返回到上一层...
Text txtValue = doc.createTextNode(sitemName);中的参数sitemName应该是sItemValue,保存节点的内容。:)

67,515

社区成员

发帖
与我相关
我的任务
社区描述
J2EE只是Java企业应用。我们需要一个跨J2SE/WEB/EJB的微容器,保护我们的业务核心组件(中间件),以延续它的生命力,而不是依赖J2SE/J2EE版本。
社区管理员
  • Java EE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧