JDOM介绍
JDOM是一个开源项目,它基于树型结构,利用纯JAVA的技术对XML文档实现解析、生成、序列化以及多种操作。使用jdom需要引入jdom.jar包。
XML生成及解析
代码如下:
1 package com.test.jdom; 2 3 import java.io.FileNotFoundException; 4 import java.io.FileOutputStream; 5 import java.io.IOException; 6 import java.util.List; 7 8 9 import org.jdom2.Document; 10 import org.jdom2.Element; 11 import org.jdom2.JDOMException; 12 import org.jdom2.input.SAXBuilder; 13 import org.jdom2.output.Format; 14 import org.jdom2.output.XMLOutputter; 15 16 public class TestJdom { 17 18 public static void main(String[] args) { 19 20 createXml(); 21 parserXml(); 22 } 23 24 public static void createXml() { 25 //文档 26 Document document = new Document(); 27 //根元素 28 Element root = new Element("conpany"); 29 //设置属性 30 root.setAttribute("name","hd"); 31 //添加根目录 32 document.setRootElement(root); 33 34 Element department = new Element("department"); 35 department.setAttribute("name","department1"); 36 //添加到根目录 37 root.addContent(department); 38 39 Element employee = new Element("employee"); 40 employee.setAttribute("name","employee1"); 41 employee.setAttribute("id","1"); 42 //设置文本 43 employee.setText("123"); 44 department.addContent(employee); 45 XMLOutputter xmlOut = new XMLOutputter(); 46 xmlOut.setFormat(Format.getPrettyFormat()); 47 try { 48 xmlOut.output(document, new FileOutputStream("src/test-jdom-create.xml")); 49 } catch (FileNotFoundException e) { 50 e.printStackTrace(); 51 } catch (IOException e) { 52 e.printStackTrace(); 53 } 54 } 55 56 public static void parserXml() { 57 // 创建一个SAXBuilder 58 SAXBuilder builder = new SAXBuilder(); 59 try { 60 // 通过输入源SAX构造一个Document 61 Document document = builder.build("src/test-jdom-create.xml"); 62 //获取根节点 63 Element root = document.getRootElement(); 64 // 获得root节点下面的所有子节点 65 List<Element> departmentList = root.getChildren(); 66 for (Element department: departmentList) { 67 // 获得节点属性 68 System.out.println(department.getName()+" "+department.getAttributeValue("name")); 69 List<Element> employeeList = department.getChildren(); 70 for (Element employee : employeeList) { 71 // 获得节点属性和文本 72 System.out.println(" " + employee.getName() + " "+ employee.getAttributeValue("name") + " "+ employee.getText()); 73 } 74 } 75 } catch (JDOMException e) { 76 System.out.println(e.getMessage()); 77 } catch (IOException e) { 78 System.out.println(e.getMessage()); 79 } 80 } 81 }
生成文本:
输出结果: