java 解析xml(dom4j.jar)

先导入jar包

<?xml version="1.0" encoding="UTF-8"?>
<companys>
    <company id="www.baidu.com">
        <name>百度</name>
        <brand>熊掌</brand>
        <size>10000</size>
    </company>
    <company id="sina.cn">
        <name>新浪</name>
        <brand>小图标</brand>
        <size>2000</size>
    </company>
</companys>
package zr.com.util;

import java.io.File;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.omg.CORBA.portable.ValueBase;

/**
 * 
 * @author LF
 *
 */
public class TestXML {
    
    public static void main(String[] args) {
        // 创建SAXReader对象
        SAXReader reader = new SAXReader();
        // 创建Document对象
        Document document = null;
        // 读取文件(xml文件)
        try {
            document = reader.read(new File("src/test.xml"));
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        // 获取跟根节点
        Element element = document.getRootElement();
        
        TestXML.getAllContent(element);
    }
    
    /**
     * 递归
     * @param node
     */
    public static void getAllContent(Element node){
        // 获取当前节点名称
        System.out.println("--当前节点:"+node.getName());
        // 获取当前节点的所有属性节点
        List<Attribute> attributes = node.attributes();
        // 遍历属性节点
        for (Attribute attribute : attributes) {
            System.err.println("属性名:"+attribute.getName()+",属性值:"+attribute.getValue());
        }
        // 获取当前节点的值
        String value = node.getText(); 
        // 如果当前节点的值不为空,则输出
        if (!"".equals(value)) {
            System.out.println("节点名:"+node.getName()+",节点的值"+value);
        }
        // 创建迭代器
        Iterator it = node.elementIterator();
        // 遍历子节点
        while (it.hasNext()) {
            Element childNode = (Element) it.next();
            // 递归
            getAllContent(childNode);
        }
    }
}
原文地址:https://www.cnblogs.com/lantu1989/p/6675219.html