• Java如何使用DOM4j解析XML呢?


    转自:

    Java如何使用DOM4j解析XML呢?

    下文讲述DOM4j解析XML的方法分享,如下所示:

    DOM4j简介

    dom4j是一个开源库
    它用于处理XML、 XPath和XSLT
    dom4j基于Java平台,使用Java的集合框架
     全面集成了DOM,SAX和JAXP
    

    例:
    使用Iterator迭代解析xml

    //测试xml文件
    
    
        hello Text1
        hello Text2
        hello Text3
        world text1
        world text2
        world text3
    
    /**
     * dom4j读取并解析xml
     */
    public class Dom4JTest2
    {
        public static void main(String[] args) throws Exception
        {
            SAXReader saxReader = new SAXReader();
            Document document = saxReader.read(new File("test.xml"));
            // 获取根元素
            Element root = document.getRootElement();
            System.out.println("Root: " + root.getName());
    
            // 获取所有子元素
            List childList = root.elements();
            System.out.println("total child count: " + childList.size());
    
            // 获取特定名称的子元素
            List childList2 = root.elements("hello");
            System.out.println("hello child: " + childList2.size());
    
            // 获取名字为指定名称的第一个子元素
            Element firstWorldElement = root.element("world");
            // 输出其属性
            System.out.println("first World Attr: "
                    + firstWorldElement.attribute(0).getName() + "="
                    + firstWorldElement.attributeValue("name"));
            System.out.println("迭代输出-----------------------");
            // 迭代输出
            for (Iterator iter = root.elementIterator(); iter.hasNext();)
            {
                Element e = (Element) iter.next();
                System.out.println(e.attributeValue("name"));
            }
            System.out.println("用DOMReader-----------------------");
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            // 注意要用完整类名
            org.w3c.dom.Document document2 = db.parse(new File("test.xml "));
            DOMReader domReader = new DOMReader();
    
            // 将JAXP的Document转换为dom4j的Document
            Document document3 = domReader.read(document2);
            Element rootElement = document3.getRootElement();
            System.out.println("Root: " + rootElement.getName());
        }
    }
  • 相关阅读:
    完全日期(蓝桥杯)
    QJsonValue的学习
    nginx 正则匹配测试工具
    HMS Core音频编辑服务音源分离与空间音频渲染,助力快速进入3D音频的世界
    线程中断机制和LockSupport
    国内BI工具五巨头有哪些?各自有哪些擅长的?
    threejs 加载各种格式的3d模型 封装
    【JavaSE】初识Java
    什么是Mirai僵尸网络
    python的中秋之美
  • 原文地址:https://blog.csdn.net/qq_25073223/article/details/126192566