zoukankan      html  css  js  c++  java
  • java 解析xml(dom4j.jar)

    先导入jar包

    <?xml version="1.0" encoding="UTF-8"?>
    <companys>
        <company id="www.baidu.com">
            <name>百度</name>
            <brand>熊掌</brand>
            <size>10000</size>
        </company>
        <company id="sina.cn">
            <name>新浪</name>
            <brand>小图标</brand>
            <size>2000</size>
        </company>
    </companys>
    package zr.com.util;
    
    import java.io.File;
    import java.util.Iterator;
    import java.util.List;
    
    import org.dom4j.Attribute;
    import org.dom4j.Document;
    import org.dom4j.DocumentException;
    import org.dom4j.Element;
    import org.dom4j.io.SAXReader;
    import org.omg.CORBA.portable.ValueBase;
    
    /**
     * 
     * @author LF
     *
     */
    public class TestXML {
        
        public static void main(String[] args) {
            // 创建SAXReader对象
            SAXReader reader = new SAXReader();
            // 创建Document对象
            Document document = null;
            // 读取文件(xml文件)
            try {
                document = reader.read(new File("src/test.xml"));
            } catch (DocumentException e) {
                e.printStackTrace();
            }
            // 获取跟根节点
            Element element = document.getRootElement();
            
            TestXML.getAllContent(element);
        }
        
        /**
         * 递归
         * @param node
         */
        public static void getAllContent(Element node){
            // 获取当前节点名称
            System.out.println("--当前节点:"+node.getName());
            // 获取当前节点的所有属性节点
            List<Attribute> attributes = node.attributes();
            // 遍历属性节点
            for (Attribute attribute : attributes) {
                System.err.println("属性名:"+attribute.getName()+",属性值:"+attribute.getValue());
            }
            // 获取当前节点的值
            String value = node.getText(); 
            // 如果当前节点的值不为空,则输出
            if (!"".equals(value)) {
                System.out.println("节点名:"+node.getName()+",节点的值"+value);
            }
            // 创建迭代器
            Iterator it = node.elementIterator();
            // 遍历子节点
            while (it.hasNext()) {
                Element childNode = (Element) it.next();
                // 递归
                getAllContent(childNode);
            }
        }
    }
  • 相关阅读:
    【设计模式】——抽象工厂模式
    【设计模式】——观察者模式
    Candy
    Two Sum
    Interleaving String
    Longest Valid Parentheses
    【设计模式】——建造者模式
    【设计模式】——外观模式
    Simplify Path
    Word Search
  • 原文地址:https://www.cnblogs.com/lantu1989/p/6675219.html
Copyright © 2011-2022 走看看