java中读出xml中里面配置的属性

一、xml属性文件书写




	
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		

		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
	

我这就没写注释了,最好在开发的时候还是写上对应的注释,让别的开发能够明白字段含义

java中读出xml中里面配置的属性_第1张图片

mapping文件放置在webapp/styles/config下,等下就要通过这个路径加载到xml文件并且读取

二、编写xml读取工具类

public class XmlUtils {

    /**
     * 根据xml解析属性
     * @param path xml路径
     * @param id mapping组id
     * @param key 键值对key标识
     * @return value key对应的value
     * @throws SAXException
     * @throws IOException
     * @throws Exception
     */
    public static String getMappingValue(String path, String id, String key)
            throws SAXException, IOException, Exception {
        if(id=="exchange_type"){
            System.out.println(key+"=================");
        }
        // 解析文件,生成document对象
        DocumentBuilder builder = DocumentBuilderFactory.newInstance()
                .newDocumentBuilder();
        Document document = builder.parse(Utils.getStringStream(Utils
                .captureHtml(path)));
        // 生成XPath对象
        XPath xpath = XPathFactory.newInstance().newXPath();

        String webTitleLang = (String) xpath.evaluate("/root/mapping[@id='"
                        + id + "']/item[@key='" + key + "']/@value", document,
                XPathConstants.STRING);
        return webTitleLang;
    }

    /**
     * 根据key取出bpm组value属性
     * @param key
     * @return
     * @throws SAXException
     * @throws IOException
     * @throws Exception
     */
    public static String getBpmMappingValue(String key)
            throws SAXException, IOException, Exception {
        key = key.trim();
        String webTitleLang = getMappingValue(Constants.PATH+"styles/config/mapping.xml","bpm",key);
        return webTitleLang;
    }

}

通过这几段代码可以获取到xml中item标签对应key的数据,这里我是获取value值,也可以对这个匹配规则进行修改。

三、测试

java中读出xml中里面配置的属性_第2张图片

你可能感兴趣的:(Java)