最近因为工作的原因,第一次接触到需要自定义XML格式文件实现数据模板(字段)配置。通过在网上查询资料并结合自己的需求设计总结了一套自定义格式XML文件读取的实现方法,希望对同样需求的开发工作者有所帮助。本方法建立在功能运用层面上,如果对实现原理感兴趣请自行查询相关技术文档(推荐)。
第一步:本文使用Dom4J工具来解析XML文件,故需引入其Maven依赖:
<dependency> <groupId>dom4j</groupId> <artifactId>dom4j</artifactId> <version>1.6.1</version> </dependency>
第二步:自定义XML格式文件(本文尽可能多的对XML文件进行多标签组和多属性设计,以便功能具有通用性),如下:
<?xml version="1.0" encoding="UTF-8"?> <templates> <template id="101"> <property fieldName="数据集名称" field="name" default="" tips="请输入名称(不少于6个字符)" fieldType="1" rules=""/> <property fieldName="简介" field="description" default="" tips="数据简介信息(不少于10个字符)" fieldType="1" rules=""/> </template> </templates>
第三步:方法实现
public Map<String,Object> readXMLTemplates(HttpServletRequest request){ String realPath = request.getServletContext().getRealPath("/"); String path = realPath + File.separator + "template" + File.separator; String fileName = "ProjectType.xml"; try{ File file = new File(path, fileName); SAXReader reader = new SAXReader(); Document doc = reader.read(file); Element root = doc.getRootElement(); Element e; // 获取 template 标签数据集 List templates = root.elements(); // 遍历每一个 template 对象 for (Iterator<?> it = templates.iterator(); it.hasNext();) { // template 对象 e = (Element) it.next(); //template 标签Id值 String id = e.attributeValue("id"); System.out.println("标签id = "+id); //获取每一个 template 标签下的 property 属性集 List properties = e.elements("property"); //对每一个 property 的属性进行遍历 for (Iterator<?> itx = properties.iterator(); itx.hasNext();) { List<Attribute> attrList = ((Element)itx.next()).attributes(); for(Attribute attribute : attrList) { System.out.println(attribute.getName()+" = "+attribute.getValue()); } } } }catch (Exception e){ e.printStackTrace(); } return null; }
Dom4J通过读取XML文件获得文档对象,通过文档对象获取XML树形结构的根节点,然后通过elements()或者elements("标签名")的方法获取当前节点下所有的子节点,最后通过attributes()方法获取每一个节点对象的属性值实现数据读取,控制台结果如下:
标签id = 101
fieldName = 数据集名称
field = name
default =
tips = 请输入名称(不少于6个字符)
fieldType = 1
rules =
fieldName = 简介
field = description
default =
tips = 数据简介信息(不少于10个字符)
fieldType = 1
rules =
以上为工具使用的总结方法,记录以作备忘。