package com;
import net.sf.json.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.net.URL;
import java.util.Iterator;
import java.util.List;
/**
* Created by dell on 2015/11/26.
*/
public class test {
public static void main(String[] args) {
Log logger= LogFactory.getLog(test.class);
File xmlFile = new File("D:/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("//OAInfo/Info");
} catch (DocumentException e) {
e.printStackTrace();
}
// for(Iterator iter = rowList.iterator();iter.hasNext();){
for(Iterator iter = rowList.iterator();iter.hasNext();){
//获得具体的Info元素
Element element = (Element)iter.next();
//获得Info元素的所有属性列表
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("Name"));
//输出:
//gfd
//如果element下有子元素,(类似width="**"),要想获得该子元素的值,可以用如下方法
if("未阅寻呼".equalsIgnoreCase(element.elementText("Name"))) {
System.out.println(element.elementText("Name"));//如果没有,输出为null。
System.out.println(element.elementText("Num"));
System.out.println(element.elementText("Url"));
}else{
break;
}
}
}
}
java 利用dom4j 解析XML文件
最新推荐文章于 2023-06-19 16:47:21 发布