利用xpath对文件信息进行读写
?????? 在项目开发中遇到了对于诸如xml,.project,.classpath等等类型的文件进行读写的问题,起初因为没接触过,所以一头雾水,无从下手。翻看了很多资料后,觉得其实原理还是挺简单的 ,下面以读写.classpath为例,贴出具体的代码。在看这些代码之前,还需要熟悉下面两个知识点:
?????? 1。xpath : xpath 不了解的同学建议看下xpath的教程:xpath? w3c教程
?????? 2。Dom4j : Dom4j 操作文件工具类,详见本人上一篇博客:操作xml文件工具类
?
首先贴出一个classpath文件的例子:
?
<?xml version="1.0" encoding="UTF-8"?><classpath><classpathentry kind="con" path="org.eclipse.jdt.USER_LIBRARY/spring"><attributes><attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/></attributes></classpathentry></classpath>
?????? 不理解上面这个文件中的代码没关系,我们只是以这个文件为例子,进行读写操作,和上面类似,在classpath节点下创建以下节点:
????????????????????????????? <classpathentry kind="aaa" path="bbb">
????????????????????????????????????? <attributes>
??? ???????????????????????????????????????? <attribute name="ccc" value="ddd"/>
????????????????????????????????????? </attributes>
????????????????????????????? </classpathentry>
?
?
?????? 步骤:1.首先根据classpath文件路径读出文档对象
????????????????? 2.读出根节点classpath
????????????????? 3.创建classpathentry节点
????????????????? 4.创建attributes节点
????????????????? 5.创建attribute节点
?
代码如下:
//根据路径获取classpath文件的文档对象(Dom4jUtil详见本人上一篇博客:操作xml文件工具类)Document document = Dom4jUtil.getDocument("c:\\.classpath");//利用xpath查找classpath节点下是否已存在kind值为aaa且path值为bbb的节点,不存在才能新增String xpath = "classpath/classpathentry[@path='bbb' and @kind='aaa']";List<?> list = document.selectNodes(xpath);if(list.size()==0){//不存在则新增//添加classpath节点下面的classpathentry节点Element root = document.getRootElement();//获取文档对象的根节点的节点对象:上面例子中,根节点为classpathMap<String, String> attMap = new HashMap<String, String>();attMap.put("path","bbb");attMap.put("kind","aaa");Dom4jUtil.createElement(root,"classpathentry",attMap ,null);Dom4jUtil.write("c:\\.classpath", document);//添加classpathentry节点下面的attributes节点Dom4jUtil.createElement((Element)document.selectNodes(xpath).get(0),"attributes",null ,null);Dom4jUtil.write("c:\\.classpath", document);//添加attributes节点下面的attribute节点String xpath1 = xpath+"/attributes";List<?> list1 = document.selectNodes(xpath1);Map<String, String> attMap2 = new HashMap<String, String>();attMap2.put("value","ddd");attMap2.put("name","ccc");Dom4jUtil.createElement((Element)list1.get(0),"attribute",attMap2 ,null);Dom4jUtil.write("c:\\.classpath", document);}?
?运行后的结果如下:
<?xml version="1.0" encoding="UTF-8"?><classpath><classpathentry kind="con" path="org.eclipse.jdt.USER_LIBRARY/spring"><attributes><attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/></attributes></classpathentry><classpathentry kind="aaa" path="bbb"><attributes><attribute name="ccc" value="ddd"/></attributes></classpathentry></classpath>
?
?