springboot(Java)读取路由权限配置文件(xml类型),笔记

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方法测试可行

 

 

 

 

 

 

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值