XML读写之JDOM

前端之家收集整理的这篇文章主要介绍了XML读写之JDOM前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

  本文先使用JDOM方式写一个简单地小例子,亲测可以运行,然后在末尾分析其优缺点。
  我们知道,DOM的设计为了适用于不同的语言,它保留了不同语言中非常相似的API。但是它并不适合于Java编程者的习惯。而JDOM作为一种轻量级API被制定,它最核心的要求是以Java为中心,只适合于Java语言,它遵循DOM的接口主要规则,除去了DOM中为了兼容各语言而与Java习惯的不同。

1.准备

  • 新建一个Java Project
  • 新建一个Java类名称为JDOMTest.java
  • 新建一个xml文件名称为student.xml,内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<root>
    <student id="1">
        <name>张三</name>
        <age>18</age>
        <gender>male</gender>
    </student>
    <student id="2">
        <name>李四</name>
        <age>19</age>
        <gender>male</gender>
    </student>
    <student id="3">
        <name>王五</name>
        <age>21</age>
        <gender>female</gender>
    </student>
</root>
  • 由于是Maven工程,所有xml都存放在src/main/resources下面
  • 引入JDOM的jar包到pom.xml
<dependency>
            <groupId>jdom</groupId>
            <artifactId>jdom</artifactId>
            <version>1.0</version>
        </dependency>

2.编码

  • Bean文件StudentBean.java
public class StudentBean {
    private String id;
    private String name;
    private String gender;
    private Integer age;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "StudentBean [id=" + id + ",name=" + name + ",gender=" + gender + ",age=" + age + "]";
    }

}
  • XML读写类:JDOMTest.java
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;

import bean.StudentBean;

public class JDOMTest {

    public static List<StudentBean> studentsList = new ArrayList<StudentBean>();

    public static void main(String[] args) {
        //遍历XML文件中的对象
        List<StudentBean> list = visitXML();
        Iterator<StudentBean> it = list.iterator();
        while (it.hasNext()) {
            System.out.println(it.next());
        }
        updateXML("src/main/resources/student.xml");
        writeXMLFile("src/main/resources/jdom.xml");
    }

    public static List<StudentBean> visitXML() {
        try {
            SAXBuilder builder = new SAXBuilder(false);
            Document document = builder.build("src/main/resources/student.xml");
            //获取根元素
            Element root = document.getRootElement();
            List<Element> students = root.getChildren("student");
            System.out.println("XML文档中共有"+students.size()+"个学生对象!");
            for(Iterator<Element> it = students.iterator();it.hasNext();) {
                Element student = it.next();
                StudentBean stu = new StudentBean();
                stu.setId(student.getAttributeValue("id"));
                stu.setName(student.getChild("name").getText());
                stu.setAge(Integer.parseInt(student.getChildText("age")));
                stu.setGender(student.getChildText("gender"));
                studentsList.add(stu);
                stu = null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return studentsList;
    }

    public static void updateXML(String fileName) {
        try {
            SAXBuilder builder = new SAXBuilder(false);
            Document document = builder.build(fileName);
            //获取根元素
            Element root = document.getRootElement();
            List<Element> students = root.getChildren("student");
            //充值元素值
            students.get(1).getChild("name").setText("mason");
            //移除元素
            students.get(0).removeChild("gender");
            //新增元素
            Element phone = new Element("phone");
            phone.setText("15555555");
            students.get(0).addContent(phone);
            XMLOutputter outputter=new XMLOutputter();
            outputter.output(document,new FileOutputStream(fileName));
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("XML文档更改成功!");
    }

    public static void writeXMLFile(String fileName) {
        //创建根节点
        Element root = new Element("fruit");
        //添加第一个元素apple
        Element apple = new Element("apple");
        Element color = new Element("color");
        color.setText("red");
        Element price = new Element("price");
        price.setText("12.2");
        apple.addContent(color);
        apple.addContent(price);
        root.addContent(apple);
        //添加第二个元素apple
        Element apple2 = new Element("apple");
        Element color2 = new Element("color");
        color2.setText("green");
        Element price2 = new Element("price");
        price2.setText("10.88");
        apple2.addContent(color2);
        apple2.addContent(price2);
        root.addContent(apple2);
        //添加第三个元素orange
        Element orange = new Element("orange");
        Element color3 = new Element("color");
        color3.setText("yellow");
        Element price3 = new Element("price");
        price3.setText("3.33");
        orange.addContent(color3);
        orange.addContent(price3);
        root.addContent(orange);
        //写入到新的XML文件
        try {
            //将根节点添加到文档中
            Document document = new Document(root);
            XMLOutputter XMLOut = new XMLOutputter(FormatXML());
            XMLOut.output(document,new FileOutputStream("src/main/resources/jdom.xml"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("XML文档写入成功!");
    }

    public static Format FormatXML(){  
        //格式化生成的xml文件,如果不进行格式化的话,生成的xml文件将会是很长的一行... 
        Format format = Format.getCompactFormat();  
        format.setEncoding("utf-8");  
        format.setIndent(" ");  
        return format;  
    } 

}

3.运行结果

  程序修改后的student.xml为:

<?xml version="1.0" encoding="UTF-8"?>
<root>
    <student id="1">
        <name>张三</name>
        <age>18</age>

    <phone>15555555</phone></student>
    <student id="2">
        <name>mason</name>
        <age>19</age>
        <gender>male</gender>
    </student>
    <student id="3">
        <name>王五</name>
        <age>21</age>
        <gender>female</gender>
    </student>
</root>

  程序自行新建的XML文件jdom.xml为:

<?xml version="1.0" encoding="utf-8"?>
<fruit>
 <apple>
  <color>red</color>
  <price>12.2</price>
 </apple>
 <apple>
  <color>green</color>
  <price>10.88</price>
 </apple>
 <orange>
  <color>yellow</color>
  <price>3.33</price>
 </orange>
</fruit>

4.结束

  优点
1.是基于树的处理XML的Java API,把树加载在内存中
2.没有向下兼容的限制,因此比DOM简单
3.速度快,缺陷少
4.具有SAX的JAVA规则
  缺点:
1.不能处理大于内存的文档
2.JDOM表示XML文档逻辑模型。不能保证每个字节真正变换。
3.针对实例文档不提供DTD与模式的任何实际模型。
4.不支持与DOM中相应遍历包
  适用场景: JDOM具有树的便利性,也有SAX的JAVA规则。在需要平衡时使用。

猜你在找的XML相关文章