1. maven introduces jdom2
<dependency> <groupId>org.jdom</groupId> <artifactId>jdom2</artifactId> <version>2.0.6</version> </dependency>
2. Examples
import java.io.FileOutputStream; import java.util.List; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.input.SAXBuilder; import org.jdom2.output.Format; import org.jdom2.output.XMLOutputter; public class MemInfoParserJDOM { /** * log4j2 logs */ protected static Logger log = LogManager.getLogger(); public static void main(String[] args) { String path = "/data/workspace/tec-demo/src/main/java/cn/tinyf/demo/xml/jdom/jdom-data.xml"; MemInfoParserJDOM dj = new MemInfoParserJDOM(); dj.createXml(path); dj.parserXml(path); } /** * Generate XML * * @param filePath * file path */ public void createXml(String filePath) { // create root node Element root = new Element("MemInfo"); root.setAttribute("class", "0501"); // create the first child node root.addContent(createElementPerson(1, "James", 32)); // create the second child node root.addContent(createElementPerson(2, "Kim", 38)); // create the second child node root.addContent(createElementPerson(3, "Joe", 24)); // The root node is added to the document Document Document document = new Document(root); try { // output to file XMLOutputter XMLOut = new XMLOutputter(); Format f = Format.getPrettyFormat(); f.setEncoding("UTF-8");// default=UTF-8 XMLOut.setFormat(f); XMLOut.output(document, new FileOutputStream(filePath)); } catch (Exception e) { log.error(e); } } /** * Create a student child node * * @param no * student ID * @param name * Name * @param age * age * @return */ private Element createElementPerson(int no, String name, int age) { Element person = new Element("person"); person.setAttribute("no", no + ""); // name child node Element nameE = new Element("name"); nameE.addContent(name); person.addContent(nameE); // age child node Element ageE = new Element("age"); ageE.addContent(age + ""); person.addContent(ageE); // return node return person; } /** * Parse XML * * @param filePath * file path */ public void parserXml(String fileName) { try { // Build the SAX parser SAXBuilder builder = new SAXBuilder(); // Parse to get the document object Document document = builder.build(fileName); Element root = document.getRootElement(); //traverse child nodes List<Element> persons = root.getChildren("person"); for (int i = 0; i < persons.size(); i++) { Element person = persons.get(i); log.info("学号:{},姓名:{},年龄:{}", person.getAttribute("no").getValue(), person.getChildText("name"), person.getChildText("age")); } } catch (Exception e) { log.error(e); } } }