用SAXReader解析xml文档本篇文章来源于:开发学院 http://edu.codepub.com 原文链接:http://edu.codepub.com/2009/1217/18796.php

使用SAXReader需要导入dom4j-full.jar包。 dom4j是一个Java的XML API,类似于jdom,用来读写XML文件的。dom4j是一个非常非常优秀的Java XML API,具有性能优异、功能强大和极端易用使用的特点,同时它也是一个开放源代码的软件,可以在SourceForge上找到它。 使用举例: 1. s.xml内容 view plaincopy to clipboardprint? 2.解析 view plaincopy to clipboardprint? import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.Iterator; import java.util.List; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; import org.dom4j.tree.AbstractAttribute; public class ReadXMLTest { public static void main(String[] args){ File xmlFile = new File("C:/s.xml"); FileInputStream fis = null; try { fis = new FileInputStream(xmlFile); } catch (FileNotFoundException e) { e.printStackTrace(); System.err.println("File is not exsit!"); } SAXReader saxReader = new SAXReader(); List rowList = null; try { //生成文档对应实体 Document doc = saxReader.read(fis); //获取指定路径下的元素列表,这里指获取所有的data下的row元素 rowList = doc.selectNodes("//data/row"); } catch (DocumentException e) { e.printStackTrace(); } for(Iterator iter = rowList.iterator();iter.hasNext();){ //获得具体的row元素 Element element = (Element)iter.next(); //获得row元素的所有属性列表 List elementList = element.attributes(); for(Iterator iter1 = elementList.iterator();iter1.hasNext();){ //将每个属性转化为一个抽象属性,然后获取其名字和值 AbstractAttribute aa = (AbstractAttribute)iter1.next(); System.out.println("Name:"+aa.getName()+";Value:"+aa.getValue()); } //输出: //Name:queryDTO.enterpriseId;Value:gfd //Name:queryDTO.loginName;Value:gdfg //Name:queryDTO.state;Value:0 System.out.println(element.getName()); //输出: //row // 取得row元素的queryDTO.enterpriseId属性的值 System.out.println(element.attributeValue("queryDTO.enterpriseId")); //输出: //gfd //如果element下有子元素,(类似width="**"),要想获得该子元素的值,可以用如下方法 System.out.println(element.elementText("width"));//因为没有,所以输出为null。 } } } 本篇文章来源于:开发学院 http://edu.codepub.com 原文链接:http://edu.codepub.com/2009/1217/18796.php
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值