站内搜索: 请输入搜索关键词

当前页面: 开发资料首页J2SE 专题关于xml的问题,急!!!!!!!!!!!在线等(100分)

关于xml的问题,急!!!!!!!!!!!在线等(100分)

摘要: 关于xml的问题,急!!!!!!!!!!!在线等(100分)


我在数据库中定义了三个字段(id,parentid,text),分别是节点,父节点,文本,现在我想用java程序读取数据后生成xml文件,建立树结构。

急急急急!!!!!!!!!!!!!!!!




帮顶


你的子节点下面还会不会再有子节点,也就是说一共有几级节点.


是啊
听说用递归
但是算法我不会
希望指导


递归就是方法自己调用自己,直到某个条件成立退出,非常浪费资源,我给你写个大概思路:
/**
* 遍历父节点pid下所有的子节点
* 参数obj是XML树的一个节点对象
*/
public boolean createXML(int pid,Object obj){
根据父节点pid去数据库查父节点id都是pid的数据;
String SQL=-#34;select *from table where pid=-#34;+pid;
执行SQL语句;
得到结果集rs;
while(rs.next()){
int ele=rs.getInt(-#34;id-#34;);
obj.add 把ele加为obj的子节点;
用递归方法调用自己,把刚取到的id和新加的子节点传进去;
createXML(ele,obj.add新加的子节点传进去);
}
return true;
}


小心某两个节点互为父节点啊。
会内存耗尽的。


jdom或者dom4j都很容易实现,几分钟的事情


帮顶


jdom将数据内存中, 根据父子关系遍历节点, 生成树即可


用DOM吧,发给你一段用DOM解析XML的代码:
public Message[] getAllMessages() {
Message returnValue[] = null;
try {
NodeList nl = doc.getElementsByTagName(-#34;message-#34;);
int length = nl.getLength();

returnValue = new Message[length];
for (int i = 0; i -#60; length; i++) {
NodeList messagelist = nl.item(i).getChildNodes();

returnValue[i] = new Message();
for (int j = 0; j -#60; messagelist.getLength(); j++) {

String nodeName = messagelist.item(j).getNodeName();

if (nodeName.equals(-#34;nickname-#34;)) {
String nodeValue = messagelist.item(j).getFirstChild().
getNodeValue();
returnValue[i].setWriterNickname(nodeValue);
} else if (nodeName.equals(-#34;writedate-#34;)) {

String nodeValue = messagelist.item(j).getFirstChild().
getNodeValue();

returnValue[i].setWriteDate(nodeValue);
} else if (nodeName.equals(-#34;context-#34;)) {

String nodeValue = messagelist.item(j).getFirstChild().
getNodeValue();

returnValue[i].setContext(nodeValue);
}
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
return returnValue;
}



也可以利用一个设计模式--组合模式,这种模式天生就有种递归的结构...



↑返回目录
前一篇: 新手请教一个applet小程序的问题,不知这个怎么初始化.....在线等
后一篇: JAVA新手求解一道算法题?得解马上结贴!