读取XML文件的两种方式--dom4j(包括xpath使用)和dom

1.参考 w3c.school或者xpath https://www.cnblogs.com/vastsum/p/5940235.html
2.dom读取 参考 https://blog.51cto.com/13479739/2313218
3.xpath需要的包

    <!-- https://mvnrepository.com/artifact/jaxen/jaxen  xpath使用的包-->
    <dependency>
      <groupId>jaxen</groupId>
      <artifactId>jaxen</artifactId>
      <version>1.1.6</version>
    </dependency>
    //dom4j读取xml
    public  static void dom4jReadXml(){
        String  sourcePath = "X:\\sofa_home\\global\\datasources.xml";
        File file = new File(sourcePath);
        SAXReader saxReader = new SAXReader();
        try {
            //需要加上包名,否则会自动识别dom包
            org.dom4j.Document read = saxReader.read(file);
            Element rootElement = read.getRootElement();
            //获得所有节点值
            System.out.println("》》》》》》》rootElement.getStringValue():"+rootElement.getStringValue());
            System.out.println("rootElement.getText()"+rootElement.getText());
            //获得所有子节点
            List<Element> elements = rootElement.elements();
            for (Element element : elements) {
                //getStringValue是该节点所有子孙节点的文本值
                System.out.println(element.getStringValue());
                //节点名称<datasource>这个名字
                System.out.println(">>>>>>element:"+element.getName());
                System.out.println(">>>>>>element:"+element.getNodeTypeName());
                List<Attribute> attributes = element.attributes();
                for (Attribute attribute : attributes) {
                    //元素属性:  <datasource id="sofa" enabled="true" dbType="ORACLE" connectType="0" dsType="hik">
                    //属性名和属性值
                    System.out.println("attribute.gename:"+attribute.getName());
                    System.out.println("attribute.gename:"+attribute.getValue());
                }

            }


        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }
  //dom4j通过xpath读取xml中的任意节点
    public static void dom4jAndXpathReadXml(){
        String  sourcePath = "X:\\sofa_home\\global\\datasources.xml";
        File file = new File(sourcePath);
        //相对路径,不分结构层次,拿所有url节点的
        String xpath  = "//testQuery";
        SAXReader saxReader = new SAXReader();
        try {
            org.dom4j.Document document = saxReader.read(file);
            //读节点在Java中使用xpath方法,主要有两点:
            //List<Node> selectNodes("xpath表达式"); 查询多个节点对象,一般使用多节点方法,查出的是Element,
            // 可以获得属性等,可选项比较多
            //Node selectSingleNode("xpath表达式"); 查询一个节点对象
            List<Element> list = document.selectNodes(xpath);
            for (Element o : list) {
                System.out.println(o.getName());
                System.out.println(o.getText());
                o.attributes();
            }
            //如果有多个匹配,则只去第一个匹配到的
            Node node = document.selectSingleNode(xpath);

            System.out.println("单节点读取:"+node.getText());
            //绝对路径,表示从跟路径或者子元素开始,一个层次结构,不读取孙元素
            //取根路径下的url元素,*是通配符,表示datasource里所有的元素
             String absolutePath = "/datasources/datasource/*";
            List<Element> list1 = document.selectNodes(absolutePath);
            for (Element element : list1) {
                System.out.print(element.getName()+"-----");
                System.out.println(element.getText());
            }
            //[]表示选择条件 @表示属性标签,带有id属性的节点,包括父节点本身
            String xpath1 = "/datasources/*[@id]";
            List<Element> list2 = document.selectNodes(xpath1);
            System.out.println(">>>>>>>>>>>>>>>>>带有id属性的节点>>>>>>>>>>>>>>..");
            for (Element element : list2) {

                System.out.println(element.getName());
                List<Attribute> attributes = element.attributes();
                for (Attribute attribute : attributes) {
                    System.out.println(attribute.getName()+"_______-");
                    System.out.println(attribute.getValue());
                }
            }
            //查找没有enabled属性的节点
            String xpath3 = "//datasource/*[not(@enabled)]";
            System.out.println("》》》》》》》》》没有enabled属性的节点》》》》》》》》》》》》");
            List<Element> list3 = document.selectNodes(xpath3);
            //*只能用来匹配元素节点,而不能匹配文本
            //text(),表示文本值,返回datasource下所有子节点的文本值,返回的是Text对象
            String xpath4 = "//datasource/*/text()";
            //通过对文本值模糊查询选择节点,查询节点下所有文本值中含有oracle字符串的节点
            String xpath5 = "//datasource/*[contains(text(),'Driver')]";
            List<Element> list5 = document.selectNodes(xpath5);
            System.out.println(">>>>>>>>>>>>>>>>测试text()模糊查询>>>>>>>>>>>");
          
            System.out.println(">>>>>>>>>>>>>>直接读取某一节点>>>>>>>>>>>>>>>>>>>>>>..");
          Node node1 = document.selectSingleNode("//datasource/poolProperties/minPoolSize");

            System.out.println(">>>>>>>>>>>读取孙节点>>>>>>>>>>>>>>>>>>>..");
            List<Element> list4 = document.selectNodes("//datasource/*/*");
     

        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }
  //方式1 w3c.DOM的方式读取
    public static void domReadXml(){
        String  sourcePath = "X:\\sofa_home\\global\\datasources.xml";
        DocumentBuilderFactory  documentBuilderFactory =    DocumentBuilderFactory.newInstance();
        try {
            File file =new File(sourcePath);
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            Document document = null;
            try {
                 document = documentBuilder.parse(file);
            } catch (SAXException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            NodeList datasource = document.getElementsByTagName("datasource");
            for (int i =0;i<datasource.getLength();i++) {
                String username = document.getElementsByTagName("username").item(i).getFirstChild().getNodeValue();
                System.out.println("用户名:"+username);
                String password = document.getElementsByTagName("password").item(i).getFirstChild().getNodeValue();
                System.out.println("密码:"+password);
            }
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        }

    }

上面测试读取的xml文件

<?xml version="1.0" encoding="UTF-8"?>

<datasources> 
  <datasource id="sofa" enabled="true" dbType="ORACLE" connectType="0" dsType="hik"> 
    <driverClassName>oracle.jdbc.OracleDriver</driverClassName>  
    <url><![CDATA[jdbc:oracle:thin:@127.0.0.1:1521/orcl]]></url>  
    <username>sofa</username>  
    <password>YWNz__CK_</password>  
    <poolProperties> 
      <minPoolSize>0</minPoolSize>  
      <maxPoolSize>600</maxPoolSize>  
      <maxIdleTime>60</maxIdleTime>  
      <acquisitionTimeout>60</acquisitionTimeout>  
      <shareTransactionConnections>false</shareTransactionConnections>  
      <acquireIncrement>2</acquireIncrement>  
      <deferConnectionRelease>true</deferConnectionRelease>  
      <testQuery>SELECT 1 FROM DUAL</testQuery> 
    </poolProperties> 
  </datasource>  
  <datasource id="acs" enabled="true" dbType="ORACLE" connectType="0" dsType="hik"> 
    <driverClassName>oracle.jdbc.OracleDriver</driverClassName>  
    <url><![CDATA[jdbc:oracle:thin:@127.0.0.1:1521/orcl]]></url>  
    <username>sofa</username>  
    <password>YWNz__CK_</password>  
    <poolProperties> 
      <minPoolSize>0</minPoolSize>  
      <maxPoolSize>600</maxPoolSize>  
      <maxIdleTime>60</maxIdleTime>  
      <acquisitionTimeout>60</acquisitionTimeout>  
      <shareTransactionConnections>false</shareTransactionConnections>  
      <acquireIncrement>2</acquireIncrement>  
      <deferConnectionRelease>true</deferConnectionRelease>  
      <testQuery>SELECT 1 FROM DUAL</testQuery> 
    </poolProperties> 
  </datasource>  
  <datasource id="fundacc" enabled="true" dbType="ORACLE" connectType="0" dsType="hik"> 
    <driverClassName>oracle.jdbc.OracleDriver</driverClassName>  
    <url><![CDATA[jdbc:oracle:thin:@127.0.0.1:1521/orcl]]></url>  
    <username>sofa</username>  
    <password>YWNz__CK_</password>  
    <poolProperties> 
      <minPoolSize>0</minPoolSize>  
      <maxPoolSize>600</maxPoolSize>  
      <maxIdleTime>60</maxIdleTime>  
      <acquisitionTimeout>60</acquisitionTimeout>  
      <shareTransactionConnections>false</shareTransactionConnections>  
      <acquireIncrement>2</acquireIncrement>  
      <deferConnectionRelease>true</deferConnectionRelease>  
      <testQuery>SELECT 1 FROM DUAL</testQuery> 
    </poolProperties> 
  </datasource> 
</datasources>

发布了88 篇原创文章 · 获赞 5 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/weixin_42410730/article/details/100567810