用SaxBuilder,Document读取XML文件,参考用
//需要dom4包,dom4j-1.X.1.jar
/**
* 根据上传路径读取配置文件,映射到PropertyVo中
* @return
* @throws IOException
* @throws JDOMException
* @throws NoSuchMethodException
* @throws SecurityException
* @throws InvocationTargetException
* @throws IllegalAccessException
* @throws IllegalArgumentException
*/
public static PropertyVo getPropertyValue(String propertyPath) throws JDOMException, IOException, SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {
PropertyVo result = new PropertyVo();
SAXBuilder builder = new SAXBuilder();
Document doc = builder.build(new File(propertyPath));//具体到XXX.xml的路径
Element rule = doc.getRootElement();
Class<? extends PropertyVo> c = result.getClass();//c必须是PropertyVo的子类
Field fieldlist[] = c.getDeclaredFields();
//自带的方法,getDeclaredFields能把包括public、private和proteced字段取出来,但是不包括父类的申明字段。
// 反射
for (int i = 1; i < fieldlist.length; i++) {
String fld = fieldlist[i].getName();
String method = "set" + fld.substring(0, 1).toUpperCase() + fld.substring(1);//set+第一个字母大写的变量名
Method meth = c.getMethod(method, fieldlist[i].getType());
//getMethod(函数名, 传入参数类型)
String str1 = fld.substring(0, getUpper(fld));
//int getUpper(String str)自己写的函数,返回String中第一个大写字母位置
String str2 = fld.substring(getUpper(fld)).toLowerCase();
//fld里找出第一个大写字母分割并小写化
Object arglist = new Object();
//根据变量类型进行简单的处理
if ("int".equals(fieldlist[i].getType().toString())) {
arglist = Integer.parseInt(rule.getChild(str1).getChildText(str2));
} else if ("boolean".equals(fieldlist[i].getType().toString())) {
arglist = Boolean.parseBoolean(rule.getChild(str1).getChildText(str2));
} else {
arglist = rule.getChild(str1).getChildText(str2);
}
meth.invoke(result, arglist);
//差不多就是result.meth(arglist);
}
return result;
}
public static int getUpper(String str) {
for (int i = 0; i < str.length(); i++) {
if (Character.isUpperCase(str.charAt(i))) {
return i;
}
}
return 0;
}
xml长这样
<rule>
<indent>
<value>4</value>
<flag>true</flag>
</indent>
<line>
<allow>?+</allow>
<size>80</size>
<flag>true</flag>
</line>
<volume>
<value>200</value>
<flag>false</flag>
</volume>
<append>
<value>4</value>
<flag>true</flag>
</append>
<comment>
<value>##</value>
<flag>true</flag>
</comment>
<name>
<pattern1>true</pattern1>
<pattern2>true</pattern2>
<pattern3>true</pattern3>
<flag>true</flag>
</name>
<parenthesis>
<flag>true</flag>
</parenthesis>
<branch>
<flag>true</flag>
</branch>
<define>
<flag>false</flag>
</define>
</rule>