欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

XML使用JDOM方式读写

程序员文章站 2022-03-03 13:07:48
...
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
<?xml version="1.0" encoding="UTF-8"?>
<student id="001" aa="xx"><name>张三</name><sex>男</sex><age>20</age></student>


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

<?xml version="1.0" encoding="UTF-8"?>
<students>
    <student id="001">
        <name>张三</name>
        <sex>男</sex>
        <age>20</age>
    </student>
    <student id="002">
        <name>李四</name>
        <sex>女</sex>
        <age>21</age>
    </student>
</students>


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