package cn.w.agent.common.util;
import java.io.File;
import java.net.URL;
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;
/**
* 参考http://blog.csdn.net/seayqrain/article/details/5024068
* @author zheng_anbang
*
*/
public class XmlReaderUtil {
private XmlReaderUtil() {
}
private static XmlReaderUtil instance;
public static XmlReaderUtil getInstance() {
if (instance == null) {
instance = new XmlReaderUtil();
}
return instance;
}
/**
* 读取绝对路径下的文件
* @param absPath
* @return
* @throws DocumentException
*/
public Document readSystemPathFile(String absPath) throws DocumentException {
File file = new File(absPath);
SAXReader reader = new SAXReader();
Document d = reader.read(file);
return d;
}
/**
* 读取类路径或者resource中的文件
* @param fileName
* @return
* @throws DocumentException
*/
public Document readClassPathFile(String fileName) throws DocumentException {
URL file = ClassLoader.getSystemResource(fileName);
SAXReader reader = new SAXReader();
Document d = reader.read(file);
return d;
/*
* Element root = d.getRootElement();
* System.out.println(root.getName()); Element foo; for (Iterator i =
* root.elementIterator("Component"); i.hasNext();) { foo = (Element)
* i.next(); if(foo.elementText("jarName").equals(f.getName())){ } }
*/
}
public Element getEle(Document d, String xpath){
List rowList = d.selectNodes(xpath);
for (Iterator iter = rowList.iterator(); iter.hasNext();) {
return (Element) iter.next();
}
return null;
}
/*
public void readEle(Document d, String xpath) {
// 获取指定路径下的元素列表,这里指获取所有的data下的row元素
List rowList = d.selectNodes(xpath);
// 获得具体的row元素
for (Iterator iter = rowList.iterator(); iter.hasNext();) {
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());
}
System.out.println(element.getName());
System.out.println(element.attributeValue("queryDTO.enterpriseId"));
System.out.println(element.elementText("width"));// 因为没有,所以输出为null。
}
}*/
public static void main(String[] args) {
try {
Document dd = XmlReaderUtil.getInstance().readClassPathFile(
"test.xml");
Document d = XmlReaderUtil
.getInstance()
.readSystemPathFile(
"D:/projects_diy2_branch_diyTheme/agent-web/src/main/resources/test.xml");
Element e = d.getRootElement();
Element ee = dd.getRootElement();
System.out.println(e.getName());
System.out.println(ee.getName());
Element ele = XmlReaderUtil.getInstance().getEle(dd, "//data/mycontext");
System.out.println(ele.getName());
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
xml文件读取工具类
最新推荐文章于 2023-09-06 11:31:47 发布