使用dom4j xml解析文件数据

image

XML

<?xml version="1.0" encoding="ISO-8859-1"?>
<contactList>
    <contact id="1" vip="true">
        <name> 潘金莲 </name>
        <gender>女</gender>
        <email>panpan@itcast.cn</email>
    </contact>
    <contact id="1" vip="false">
        <name> 武松 </name>
        <gender>男</gender>
        <email>wusong@itcast.cn</email>
    </contact>
    <contact id="1" vip="true">
        <name> 武大郎 </name>
        <gender>男</gender>
        <email>wuda@itcast.cn</email>
    </contact>
</contactList>

dom4j

package dom4j;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.junit.Test;

import java.io.InputStream;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class start {
    @Test
    public void parseXMLData() throws Exception {
        //1. 创建一个Dom4j的解析器对象,代表了整个dom4j框架
        SAXReader saxReader = new SAXReader();
        //2. 把XML文件加载到内存中成为一个Document文档对象
        //Document document = saxReader.read(new File("xml-app\\src\\Contact.xml"));
        InputStream is = start.class.getResourceAsStream("/contact.xml");
        Document document = saxReader.read(is);
        //3. 获取根元素对象
        Element root = document.getRootElement();
        System.out.println(root);
        // 默认获取第一个元素对象
        Element contact = root.element("contact");
        //获取了元素文本
        System.out.println(contact.elementText("name"));
        // 去除前后空格
        System.out.println(contact.elementTextTrim("name"));
        // 获取当前元素下的子元素对象
        Element email = contact.element("email");
        System.out.println(email.getText());
        //根据元素获取属性值
        Attribute idAttr = contact.attribute("id");
        System.out.println(idAttr.getName() + "-->" + idAttr.getValue());
        //直接获取属性值
        System.out.println(contact.attributeValue("id"));
        System.out.println(contact.attributeValue("vip"));
    }
}
posted @ 2022-09-02 02:42  ajajaz  阅读(170)  评论(0编辑  收藏  举报