XML使用JDOM方式读写

阅读更多
1. XML使用JDOM方式读写

JDOM是一种使用XML(标准通用标记语言下的一个子集)的独特Java工具包,用于快速开发XML应用程序。
JDOM官方网站:http://www.jdom.org/
JDOM生成和遍历xml文件。生成xml无法格式化。


1.1 XML使用JDOM方式生成XML文件

引入jdom
新建Folder,导入jdom所用的jar包,右键 --> Build Path --> Add To Build Path
jdom-2.0.5.jar


package com.andrew.xml;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.jdom2.Attribute;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.output.XMLOutputter;
public class JDOM01 {
    public static void main(String[] args) {
        Element student = new Element("student");
        Attribute id = new Attribute("id", "001");
        Attribute aa = new Attribute("aa", "xx");
        student.setAttribute(id);
        student.setAttribute(aa);
        Element name = new Element("name");
        name.setText("张三");
        student.addContent(name);
        Element sex = new Element("sex");
        sex.setText("男");
        student.addContent(sex);
        Element age = new Element("age");
        age.setText("20");
        student.addContent(age);
        Document document = new Document(student);
        XMLOutputter out = new XMLOutputter();
        out.setFormat(out.getFormat().setEncoding("UTF-8"));
        try {
            out.output(document, new FileOutputStream("src/studentJDOMOut.xml"));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
运行结果:
在src在生成studentJDOMOut.xml

张三20


1.2 XML使用JDOM方式读取XML文件



    
        张三
        
        20
    
    
        李四
        
        21
    



package com.andrew.xml;
import java.util.List;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;
public class JDOM02 {
    public static void main(String[] args) throws Exception {
        SAXBuilder builder = new SAXBuilder();
        Document document = builder.build("src/studentsSax.xml");
        Element students = document.getRootElement();
        List studentList = students.getChildren("student");
        for (int i = 0; i < studentList.size(); i++) {
            Element student = (Element) studentList.get(i);
            String id = student.getAttributeValue("id");
            String name = student.getChildText("name");
            String sex = student.getChildText("sex");
            String age = student.getChildText("age");
            System.out.println("学号:" + id + ";姓名:" + name + ";性别:" + sex + ";年龄:" + age);
        }
    }
}
运行结果:
学号:001;姓名:张三;性别:男;年龄:20
学号:002;姓名:李四;性别:女;年龄:21

你可能感兴趣的:(xml)