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

Java解析xml文件之JDOM

程序员文章站 2022-05-28 10:44:53
...

本篇博客主要使用实例讲解如何使用jdom解析xml文件,不会对源码做分析。直接结合代码进行说明。
测试解析的xml文件如下:

<?xml version="1.0" encoding="UTF-8"?>
<changeFileName>
    <transactionInfo>
        <detail name="sourceDirectory" value="C:\log"></detail>
        <detail name="destDirectory" value="C:\log"></detail>
        <detail name="timeSerialNumer" value="20180521"></detail>
        <detail name="indexSerialNumber" value="10"></detail>
        <detail name="databaseUser" value="zhuyuqiang"></detail>
        <detail name="tableName" value=""></detail>
        <detail name="userFileNameAsTableName" value="true"></detail>
        <detail name="userUM" value="zhuyuqiang296"></detail>
        <detail name="fileType" value=".sql"></detail>
        <detail name="splitSymbol" value="_"></detail>
    </transactionInfo>
</changeFileName>

看一下解析xml的方法:

//传入待解析的xml文件名
private static List<TransactionInfo> parserByJdom(String configFileName) {
        SAXBuilder builder = new SAXBuilder();
        List<TransactionInfo> infos = new ArrayList<>();
        try {
            InputStreamReader isr = new InputStreamReader(new FileInputStream(new File(configFileName)),"UTF-8");
            //通过SAXBuilder对xml的输入流进行解析生成Document对象
            org.jdom.Document document = builder.build(isr);
            //获取根元素
            org.jdom.Element root = document.getRootElement();
            //根据标签名,获取指定符合条件的所有元素
            List<org.jdom.Element> elements = root.getChildren("transactionInfo");
            //遍历子标签,解析内容
            for(org.jdom.Element element : elements){
                List<org.jdom.Element>es = element.getChildren();
                TransactionInfo info = new TransactionInfo();
                for(org.jdom.Element e : es){
                    String propertyName = e.getAttribute("name").getValue();
                    String propertyValue = e.getAttribute("value").getValue();
                    populateBean(info,propertyName,propertyValue);
                }
                infos.add(info);
            }
        } catch (JDOMException | IOException e) {
            log.info(e.getMessage());
        } catch (IllegalAccessException e) {
            log.info(e.getMessage());
        } catch (NoSuchFieldException e) {
            log.info(e.getMessage());
        }
        return infos;
    }

JDOM好像是对SAX的封装,使用起来更加方便。
打印出的解析封装后的TransactionInfo 信息如下:

[ sourceDirectory = C:\log, destDirectory = C:\log , timeSerialNumber = 20180521 , indexSerialNumber = 10 , databaseUser = zhuyuqiang , tableName = , userFileNameAsTableName = true , userUM = zhuyuqiang296 , fileType = .sql , splitSymbol = _ ]
通过打印的信息,方法已经将xml的所有信息成功解析了。