dom4j对xml文件的基本操作
对xml文件的操作,有个很好的开源框架,dom4j,使用了大量的接口,
这里用常用的接口对xml文件进行了满足与xml平常操作需要
?
创建xml
?
public static void createDocument(String xmlName) {Document document = DocumentHelper.createDocument();Element rootElement = document.addElement("students");// 设置根节点rootElement.addComment("this is a root");// 添加注释Element studentElement = rootElement.addElement("student");// 添加子节点studentElement.addAttribute("name", "kaka");// 添加属性Element ageElement = studentElement.addElement("age");ageElement.addText("28");// 添加文本节点createXml(document, xmlName);}public static void createXml(Document document, String xmlName) {try {OutputStream out = new FileOutputStream(new File(xmlName));// 输出流OutputFormat format = OutputFormat.createPrettyPrint();// 格式设置format.setEncoding("gb2312");XMLWriter writer = new XMLWriter(out, format);// xml写入流writer.write(document);// 把document对象写入到文件里writer.flush();// 刷新} catch (Exception e) {System.out.println("程序发生异常");System.exit(0);}}
?
创建后结果为:
?
?
<?xml version="1.0" encoding="gb2312"?><students> <!--this is a root--> <student name="kaka"> <age>28</age> </student></students>?
?
?
修改xml文件
?
public static void modifyXMLFile(String fileName) {SAXReader saxReader = new SAXReader();try {Document document = saxReader.read(new File(fileName));// 读取xml文档List<?> listAttribute = document.selectNodes("/students/student/@name");// 用xpath查找节点student的属性for (int i = 0; i < listAttribute.size(); i++) {Attribute attribute = (Attribute) listAttribute.get(i);if (attribute.getValue().equals("kaka")) {attribute.setValue("C罗");}}List<?> listElement = document.selectNodes("/students/student/age");// 用于查找节点age的内容for (int i = 0; i < listElement.size(); i++) {Element element = (Element) listElement.get(i);if (element.getText().equals("28")) {element.setText("29");}}createXml(document, fileName);} catch (Exception e) {System.out.println("发生异常");System.exit(0);}}
?
修改后结果为:
?
<?xml version="1.0" encoding="gb2312"?><students> <!--this is a root--> <student name="C罗"> <age>29</age> </student></students>?
?
?
?
?删除文件节点
?
public static void deleteElement(String fileName) {SAXReader saxReader = new SAXReader();try {Document document = saxReader.read(new File(fileName));// 读取xml文档List<?> listStuElement = document.selectNodes("/students/student");// 用于查找节点student的内容for (int i = 0; i < listStuElement.size(); i++) {Element studentElement = (Element) listStuElement.get(i);//每个student节点信息存下来List<?> listAgeElement = studentElement.selectNodes("age");//当前student节点下age节点for(int j=0;j<listAgeElement.size();j++){Element age = (Element) listAgeElement.get(j);if(age.getText().equals("29")){studentElement.remove(age);//删除节点}}}createXml(document, fileName);} catch (Exception e) {System.out.println("发生异常");System.exit(0);}}
?
?删除节点结果为:
?
?
<?xml version="1.0" encoding="gb2312"?>
?
<students>
? <!--this is a root-->
? <student name="C罗"></student>
</students>
?
?