递归获取每个标签
package test; import java.io.File; import java.util.List; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; public class test { public static void main(String[] args) { //1.获取dom4j解析对象 SAXReader reader = new SAXReader(); //2.获取要解析的xml文件 try { Document document = reader.read(new File("./src/student.xml")); //3.获取根标签 Element rootElement = document.getRootElement(); getEachElement(rootElement); } catch (DocumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void getEachElement(Element element) { System.out.println(element.getName()); List<Element> elements = element.elements(); if (elements!=null) { for (Element element2 : elements) { getEachElement(element2); } } } }
运行结果
获取标签属性
方法一:(foreach遍历)
1 List<Element> elements = rootElement.elements(); 2 for (Element element :elements) { 3 String id = element.attributeValue("id"); 4 String message = element.attributeValue("message"); 5 System.out.println(id+" "+message); 6 }
方法二:(迭代器获取)
1 List<Element> elements = rootElement.elements(); 2 for (Element element :elements) { 3 4 Iterator attributeIterator = element.attributeIterator(); 5 while (attributeIterator.hasNext()) { 6 Attribute attribute = (Attribute)attributeIterator.next(); 7 8 String name = attribute.getName(); 9 String value = attribute.getValue(); 10 11 System.out.println(name+" "+value); 12 13 } 14 15 }
把XML写在本地文件
1 Document docuement = reader.read(new File("./src/student.xml")); 2 FileOutputStream fileOutputStream = new FileOutputStream("C:\message.xml"); 3 4 OutputFormat outputFormat = OutputFormat.createPrettyPrint(); 5 XMLWriter xmlWriter = new XMLWriter(fileOutputStream,outputFormat); 6 outputFormat.setEncoding("utf-8"); 7 xmlWriter.write(docuement); 8 fileOutputStream.close(); 9 xmlWriter.close();