• java 解析 xml 文件


      学习下解析 xml 文件,这里用到了 org.dom4j 这个 jar 包,使用 eclipse 没有这个包的小伙伴可以去下个 jar 包,然后复制到项目路径下,右键 jar 包后 build path,add build path 即可。

      来引入相关依赖:

    import java.io.File;
    import java.util.List;
    
    import org.dom4j.Attribute;
    import org.dom4j.Document;
    import org.dom4j.Element;
    import org.dom4j.io.SAXReader;

      注意会抛错,这里 throws 一下:

    public static void main (String[] args) throws Exception{
    
    }

      初始化变量:(这里我们使用的是 List 列表的方式进行解析)

    SAXReader reader = new SAXReader();
    File file = new File("***.xml");
    Document document = reader.read(file);
    Element root = document.getRootElement();
    List<Element> childElements = root.elements();

      循环进行打印:

    for (Element child : childElements) {
        List<Attribute> attributeList = child.attributes();
        for(Attribute attr : attributeList) {
            System.out.println(attr.getName() + ": " + attr.getValue());
        }
        List<Element> elementList = child.elements();
        for (Element ele : elementList) {
            System.out.println(ele.getName() + ": " + ele.getText());
        }
    }

      还是很 easy 的嗷~

      xml文件中结构类似这样:

    <?xml version="1.0" encoding="UTF-8"?> 
    <books> 
       <book id="001"> 
          <title>Harry Potter</title> 
          <author>J K. Rowling</author> 
       </book> 
       <book id="002"> 
          <title>Learning XML</title> 
          <author>Erik T. Ray</author> 
       </book> 
    </books> 
  • 相关阅读:
    window.onload和document.ready/jquery页面加载事件等的区别
    JAVA面试题大全
    BIO NIO AIO的知识扫盲
    类的加载过程详细解释
    nginx的Rewrite和其他相关配置
    【微服务架构设计】DDD
    【重构】
    【多线程】Lock接口与其实现类
    【三方件】汇总
    【SpringBoot-SpringSecurity】安全响应头+防攻击 ~~ TODO
  • 原文地址:https://www.cnblogs.com/guofan/p/6842090.html
Copyright © 2020-2023  润新知