您的位置:首页 > 其它

JDOM读取XML配置文件--单例模式

2008-12-15 15:47 337 查看
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.JDOMParseException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;

public class TestJDOM {

private static TestJDOM instance = null;

private TestJDOM(){

}

public static synchronized TestJDOM getInstance() {
if (instance==null)
instance = new TestJDOM();
return instance;
}

public String[] parshString(String str){
if(str!=null&&!str.equals("")){
String[] result = str.split(";");
return result;
}else
return null;
}

public String getProperty(Element ParentElement,String[] xPath,int flag){
String result = "";
int index = xPath.length-flag;
String s = xPath[index];
List parentList=ParentElement.getChildren(xPath[index]);
for (Iterator iter = parentList.iterator(); iter.hasNext();) {
Element element = (Element) iter.next();
//List list=element.getChildren(xPath[index]);
if(flag!=1){
flag--;
result = getProperty(element,xPath,flag);
}else{
result=element.getText();
}
}
return result;
}

public String getProperty(String file,String path){
String[] xPath = parshString(path);
//String xmlpath="library.xml";
String result = "";
SAXBuilder builder=new SAXBuilder(false);
try {
Document doc= builder.build(file);
Element element=doc.getRootElement();
result = getProperty(element,xPath,xPath.length);
} catch (JDOMParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JDOMException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(result);
return result;
}

public String getProperty(String path){
String[] xPath = parshString(path);
String xmlpath="library.xml";
String result = "";
SAXBuilder builder=new SAXBuilder(false);
try {
Document doc= builder.build(xmlpath);
Element element=doc.getRootElement();
result = getProperty(element,xPath,xPath.length);
} catch (JDOMParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JDOMException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(result);
return result;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: