zoukankan      html  css  js  c++  java
  • Dom解析xml源代码

    import java.io.File;
    import java.io.IOException;
    
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.ParserConfigurationException;
    
    import org.w3c.dom.*;
    import org.xml.sax.SAXException;
    
    
    public class DomXmlTest {
    
        /**
         * @param args
         */
        public static void main(String[] args) {
            DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
            try {
                DocumentBuilder db=dbf.newDocumentBuilder();
                File f=new File("c:/bb.xml");
                Document doc=db.parse(f);
                NodeList nl=doc.getElementsByTagName("student");
                int len=nl.getLength();
                for(int i=0;i<len;i++){
                    Element elt=(Element) nl.item(i);
                    Node eltName=(Node) elt.getElementsByTagName("name").item(0);
                    Node eltAge=(Node) elt.getElementsByTagName("age").item(0);
                    System.out.println("name:"+eltName.getFirstChild().getNodeValue());
                    System.out.println("age:"+eltAge.getFirstChild().getNodeValue());
                }
            
            
            } catch (ParserConfigurationException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (SAXException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            
        }
    
    }

    xml文件

    <?xml version="1.0" encoding="UTF-8"?>
    <students>
        <student sn="01">
            <name>contextConfigLocation</name>
            <age>classpath:spring_config/spring*.xml</age>
        </student>
        <student sn="02">
            <name>AREACODE</name>
            <age>410526</age>
        </student>
    </students>
  • 相关阅读:
    Android中查找一个Layout中指定的子控件
    常用代码
    数据库连接池配置
    分享一个电子书网站
    怎么快速入手一个项目在没有人指导的情况下
    压测如何观测jvm,就是使用jmx来实现jvm监控
    工具类
    APP开发和web开发的区别
    网站切流量
    互联网主题分析
  • 原文地址:https://www.cnblogs.com/LT0314/p/3770197.html
Copyright © 2011-2022 走看看