1.auth.xml示例:
<?xml version="1.0" encoding="UTF-8"?>
<authList>
<auth>
<authId>baseSet</authId>
<authName>基础设置</authName>
<authType>M</authType>
<children>
<authId>chargeItem</authId>
<authName>收费项目</authName>
<authType>M</authType>
<children>
<authId>search</authId>
<authName>查询</authName>
<authType>B</authType>
</children>
<children>
<authId>create</authId>
<authName>新建</authName>
<authType>B</authType>
</children>
<children>
<authId>modify</authId>
<authName>修改</authName>
<authType>B</authType>
</children>
<children>
<authId>delete</authId>
<authName>删除</authName>
<authType>B</authType>
</children>
</children>
</auth>
</authList>
2.读取xml文件
/**
* 读取xml文件配置值
* @return
*/
@SuppressWarnings("rawtypes")
public static List parseXml(){
SAXReader reader = new SAXReader();
try {
Document document = reader.read("src/main/resources/config/config.xml");
Element root = document.getRootElement();
Element element = null ;
List list = new ArrayList<>();
String pId = "";
for( Iterator itr = root.elementIterator(); itr.hasNext();){// 获取所有根节点
element = (Element)itr.next();
// System.out.println(element);
treeWalk(element,list,pId);// 递归获取当前根节点下的所有节点值
}
System.out.println(list);
return list;
} catch (DocumentException e) {
e.printStackTrace();
return null;
}
}
需要注意的是reader读取方式在项目打成jar后会报错,找不到文件
解决办法:Document document = reader.read("classpath:auth.xml");路径根据你项目xml文件处于的实际路径来写,我的是在resource目录下
3.递归方法
@SuppressWarnings({ "unchecked", "rawtypes" })
public static void treeWalk(Element element,List list,String pId) {
Map map = new HashMap<>();
if(!pId.equals("")){
map.put("pid", pId);
}
for ( int i=0, size = element.nodeCount(); i < size; i++){
Node node = element.node(i);
if(node.getName() == null)continue;
if("authId".equals(node.getName())){
map.put("authId", node.getText());
pId = node.getText();
}
if("authName".equals(node.getName()))map.put("authName", node.getText());
if("authType".equals(node.getName()))map.put("authType", node.getText());
if (node instanceof Element &&node.getName().equals("children")) treeWalk ((Element)node,list,pId);
}
list.add(0,map);
// System.out.println(list);
}
结束,main方法测试可行