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文件讀取工具類
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.