一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

jdom解析xml二种方法

时间:2011-01-20 编辑:简简单单 来源:一聚教程网

通过jdom来解析,需要借助第三方的组件.jdom.jar,网上有1.0的版本下载,这是我前几天才写的一段

public static hashmap readxml(string path) {
 
  hashmap hamap = new hashmap();
 
  try {
   document document = new saxreader().read(path);//找到xml的路径
   element root = document.getrootelement();//得到根节点
   list member = root.elements();
   if (null == member || 0 == member.size()) {
    system.out.println("没有子模块定义,系统退出");
    return null;
   }
           //读取xml中的值
   string name;
   string classname;
   for (object e : member) {
    name = ((element) e).attribute("name").getvalue();
    classname = ((element) e).attribute("class").getvalue();
    hamap.put(name, classname);
   }
   return hamap;
  } catch (documentexception e) {
   // todo auto-generated catch block
   e.printstacktrace();
   return null;
  }
 
 }

处理文件

package cn.com.jdom;

import java.io.file;
import java.io.ioexception;
import java.util.iterator;
import java.util.list;

import org.jdom.attribute;
import org.jdom.document;
import org.jdom.element;
import org.jdom.jdomexception;
import org.jdom.processinginstruction;
import org.jdom.input.saxbuilder;

import com.sun.xml.internal.bind.v2.runtime.name;

/**
 * jdom解析xml文件
 *
 * @author 黄根华
 *
 */
public class jdomxml {

 public jdomxml() {
 }

 /**
  * 解析xml文件
  * @param xmlfile
  */
 public void parsexml(file xmlfile) {
  saxbuilder sax = new saxbuilder();//在内存中建立一个sax文档模型
  try {
   document xmldom = sax.build(xmlfile);//创建文档
   //获得文件的根元素
   element root = xmldom.getrootelement();
   system.out.println("根元素是:"+root.getname());
  
   //获得根元素的子节点
   list childlist = root.getchildren();
   iterator listit = childlist.iterator();
   while(listit.hasnext()){
    element element = (element)listit.next();
    system.out.println("孩子结点是:"+element.getname());
   }
  
   //获得第一个孩子结点
   element firstchild = (element) childlist.get(0);
   //获得孩子结点的属性
   list attrlist = firstchild.getattributes();
   iterator attrit = attrlist.iterator();
   while(attrit.hasnext()){
    attribute  attr = (attribute ) attrit.next();
    system.out.println("第一个元素的属性是:"+attr.getname());
    //获得属性的值
    system.out.println("属性的值是:"+attr.getvalue());
    //获得属性的类型
    system.out.println("属性的类型是:"+attr.getattributetype());
   }
  
   list sonlist = firstchild.getchildren();
   iterator sonit = sonlist.iterator();
   while(sonit.hasnext()){
    element temp = (element)sonit.next();
    system.out.println("属性"+temp.getname()+"的值是:"+temp.getvalue());
   }
  
  
  } catch (jdomexception e) {
   e.printstacktrace();
  } catch (ioexception e) {
   e.printstacktrace();
  }
 }
 
 public static void main(string[] args) {
  jdomxml test = new jdomxml();
  test.parsexml(new file("persons.xml"));
 }
}

下面是xml文件:



 
  lhu
  89
 

安徽淮北

 
 
 
 
  we
  56
 
北京海淀

 
 

 

热门栏目