当前位置: 代码迷 >> J2SE >> dom4j 读xml有关问题有关问题!
  详细解决方案

dom4j 读xml有关问题有关问题!

热度:2514   发布时间:2013-02-25 00:00:00.0
dom4j 读xml问题问题!急急急
xml 格式如下
<root>
  <crawler>
  <domain>
  <page></page>
  <page></page>
  </domain>

  <content>
  <user></user>
  <user></user>
  </content>
  </crawler>
</root>


下面是读取的代码

 SAXReader reader = new SAXReader();
 Document doc = reader.read(new FileInputStream(file),"UTF-8");
 Element root = doc.getRootElement();

 List crawlerElements=root.elements("crawler");
 for(int i = 0;i<crawlerElements.size();i++){
  Element crawlerElement=(Element)crawlerElements.get(i);

  List domainElements = crawlerElement.elements("domain");
  List postElements = crawlerElement.elements("content");

}
  List postElements = crawlerElement.elements("content");

 为什么取这个节点取不到呢?? 打印的信息为null 是不是方法用错了 大家帮忙看下 急急急!!!

------解决方案--------------------------------------------------------
我用你的程序读,是读得到的哦。代码如下:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class DomTest {

public static void main(String args[]) {
SAXReader reader = new SAXReader();
File file = new File("d:/domtest.xml");
Document doc;
try {
doc = reader.read(new FileInputStream(file), "UTF-8");
Element root = doc.getRootElement();

List crawlerElements = root.elements("crawler");
for (int i = 0; i < crawlerElements.size(); i++) {
Element crawlerElement = (Element) crawlerElements.get(i);

List domainElements = crawlerElement.elements("domain");
List postElements = crawlerElement.elements("content");
System.out.println(postElements.size());
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
  相关解决方案