最近项目中需要添加一个给客户发送消息的功能,需要把消息模板放在xml文件中,模板如下:
<?xml version="1.0"?>
<root>
<name>张三</name>
<age>23</age>
<notice>尊敬的 {0} 用户,您好:平台撤销了 {1} 产品下的 {2}、{3} 服务,请您根据情况进行修改!</notice>
</root>
需要在相对应的位置上输入用户名、产品名、服务名等信息,写了一个解析xml的工具类,如下:
package bean;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
public class XMLUtil
{
private final static String PATH = "C:\\Users\\DOG\\Desktop\\XML.xml";
private final static Map<String, String> MAP = new HashMap<String, String>();
private volatile static XMLUtil util = null;
private XMLUtil()
{
init();
}
public static XMLUtil getInstance()
{
if(util == null)
{
synchronized(XMLUtil.class)
{
if(util == null)
{
util = new XMLUtil();
}
}
}
return util;
}
private void init()
{
try
{
Document document = new SAXReader().read(new FileInputStream(new File(PATH)));
Element rootElement = document.getRootElement();
for(Object obj:rootElement.elements())
{
Element element = (Element)obj;
MAP.put(element.getName().trim(), element.getText().trim());
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (DocumentException e)
{
e.printStackTrace();
}
}
public String getValue(String key)
{
if("".equals(key) || key == null)
{
return "key值为空!";
}
else
{
if(MAP.get(key) == null)
{
return key+"对应的值为空!";
}
}
return MAP.get(key);
}
public String getValue(String key,Object...arg)
{
if("".equals(key) || key == null)
{
return "key值为空!";
}
else
{
if(getValue(key) == null)
{
return key+"对应的值为空!";
}
}
//重新定义一个format方法
return format(getValue(key), arg);
// jdk封装自带有往{}里传值的方法,MessageFormat.format(String str,Object[] obj)
// return MessageFormat.format(getValue(key), arg);
}
private String format(String key,Object...obj)
{
char[] ch = key.toCharArray();
int count = 0;
for(int i=0;i<ch.length;i++)
{
if('{' == ch[i])
{
count++;
}
}
String a = key;
for(int i=0;i<count;i++)
{
a = a.replace("{"+i+"}", (String)obj[i]);
}
return a;
}
}
只需把不定参数传入,即可调用该方法,测试一下:
package bean;
public class Test
{
public static void main(String[] args)
{
String message = XMLUtil.getInstance().getValue("notice", "张三","微信","发红包","收红包");
System.out.println(message);
}
}
输出结果如下:
尊敬的 张三 用户,您好:平台撤销了 微信 产品下的 发红包、收红包 服务,请您根据情况进行修改!