使用dom4j操作xml文件

本文介绍了一个使用Java编写的程序,该程序通过DOM4J库解析XML文件并打印出其元素名称、文本内容及属性信息。文章展示了如何读取指定路径下的XML文件,并递归地遍历所有元素。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package xuboTest;

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

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class XmlFileOperateAction {
    
    private static final Log log = LogFactory.getLog(XmlFileOperateAction.class);
    
    @SuppressWarnings("unchecked")
    public static void main(String args[]){
        String filePath2 = System.getProperty("user.dir")+"/WebContent/modules/student.xml";
        SAXReader reader = new SAXReader();
        Document document;
        try {
            document = reader.read(new File(filePath2));
            Element root = document.getRootElement();
            printData(root);
        } catch (DocumentException e) {
            log.error("出错了,麻痹的", e);
        }
        
        
    }
    
    @SuppressWarnings("unchecked")
    private static void printData(Element e){
        
        //打印自己的数据
        if(e.isRootElement()){
            System.out.println(e.getName()+" :  ");
        }else{
            System.out.println(e.getName()+" : "+e.getText());
        }
        List<Attribute> attributs = e.attributes();
        
        for(Attribute attr : attributs){
            System.out.println("*******"+attr.getName()+":"+attr.getValue());
        }
        //如果有子节点,就循环子节点
        List<Element> elements = e.elements();
        if(elements.size()>0){
            for(Element ex : elements){
                printData(ex);
            }
        }
    }
    
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值