上一章我们说道config.java 类要读取config.xml文件的数据,但是不能跨文件类型读取,所以要用的解析xml文件标签数据类-XMLParase
package com.Pcitc.Ep_AutoTets.PublicClass;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
/**
* 解析XML文件
* @author Administrator
*
*/
public class XMLParase {
private Document document;
private String filePath;
/**
* 构造函数初始 加载文件
* @param filePath
*/
public XMLParase(String filePath)
{
this.filePath=filePath;
this.Load(this.filePath);
}
/**
* 创建file对象
* @param filePath 文件路径
*/
public void Load(String filePath)
{
File file =new File(filePath);
if(file.exists())
{
SAXReader saxReader =new SAXReader();
try
{
document =saxReader.read(file);
} catch (DocumentException e)
{
Log.logError("XMLParase.Load-"+filePath+"文件解析错误!请检查文件");
e.printStackTrace();
;
}
}
else
{
Log.logError("XMLParase.Load-"+filePath+"文件不存在!");
}
}
/**
* 得到一级对象
* @param elementPath
* @return
*/
public Element getElementObject(String elementPath)
{
try{
return (Element) document.selectSingleNode(elementPath);
}
catch(Error e)
{
Log.logError(e.getMessage());
Log.logError(this.getClass().getSimpleName()+".getElementObject:common节点获取异常请检查文件");
return null;
}
}
/**得到一级对象文本内容
*
*/
public String getElementText(String elementPath)
{
Element element =this.getElementObject(elementPath);
if(element!=null)
{
return element.getTextTrim();
}
else
{
Log.logError("XMLParase.getElementText-"+elementPath+"找不到定位元素");
String message="找不到元素";
return message;
}
}
@SuppressWarnings("unchecked")
public List<Element> getElementObjects(String elementPath)
{
try
{
return document.selectNodes(elementPath);
}
catch(Error e )
{
Log.logError(e.getMessage());
Log.logError(this.getClass().getSimpleName()+".getElementObjects:获得与函数同名节点数据错误,请检查文件");
return null;
}
}
@SuppressWarnings("unchecked")
public Map<String, String> getChildrenInfoByElement(Element element)
{
try{
Map<String, String> map=new HashMap<String, String>();
List<Element> children =element.elements();
for(Element e : children)
{
map.put(e.getName(),e.getText());
}
return map;
}
catch(Error e)
{
Log.logError(e.getMessage());
Log.logError(this.getClass().getSimpleName()+".getChildrenInfoByElement:common子节点对象获取异常请检查文件");
return null;
}
}
}
其中有关于log 的我们将在以后的章节讲述

浙公网安备 33010602011771号