zoukankan      html  css  js  c++  java
  • XML 04 dom4j Element和Attribute类

    以解析NewFile.xml 中的数据为例

    import org.dom4j.DocumentException;
    import org.dom4j.Element;
    import org.dom4j.io.SAXReader;
    
    public class ParseXML{
          public static void main(String[] args) throws Exceptions{
                SAXReader reader = new SAXReader();
                Document document = reader.read("src/NewFile.xml");
    
                Element root = document.getRootElement();
    
                Iterator<Element> it = root.elementIterator();  //在本例中, 获取到了根元素, goodslist 
                while(it.hasNext()){
                        Element ele = it.next();  //在本例中, 获取到了第一个子元素, good
       /* 获取指定标签下的指定标签 */
                if(ele.getName().equals("good"))  //  检查
    元素名称是否为good
                {  
                  Element name = ele.element("name");  //获取到了good下名字为name(商品名称)的元素
                  if(name != null)
                    System.out.println(name.getText());  //输出商品名称的内容
                }
    
                        System.out.println(ele.getName());
                        Iterator<Attribute> attributes = ele.attributeIterator();
                        while(attributes.hasNext()){
                            Attribute ab = attribute.next();
                            System.out.println(ab.getName()+":"+ab.getValue());
                        }
                }
           /*
            Element ele = null;
            ele.elementIterator("good");  //遍历所有名字为good的子元素
           
            Attribute ab = null;
            ab.getName();   //获取属性的名字
            ab.getValue();  //获取属性的值 
           ab.getDocument(); //得到所在的文档对象

           */ } }

    /* Output:
      香蕉
      good
      id:1001
      production_date:2018-4-1
    苹果
      good
      id:1002
      ...
    */

    NewFile.xml

    <?xml version="1.0" encoding="UTF-8"?>  
    <goodslist>  
        <good id="1001" production_date="2018-4-1"> 
             <price>12</price>  
             <name>香蕉</name>
             <place>广州</place>
        </good>     
        <good id="1002">
             <price>39</price>  
             <name>苹果</name>
             <place>北京</place>
        </good>     
        <good id="1003">
             <price>33</price>  
             <name>芒果</name>  
             <place>上海</place>
        </good>        
    </goodslist>
  • 相关阅读:
    Nodejs exec和spawn的区别
    VC++每个版本对应的库
    在cmd启动一个win32程序,printf把信息输出到启运它的那个CMD窗口
    window 控制台解决中文乱码
    NW.js 桌面应用程序
    C++ Addon Async 异步机制
    Node bak
    nodejs electron 创建桌面应用
    跨平台桌面程序框架Electron
    js post 下载文件
  • 原文地址:https://www.cnblogs.com/JasperZhao/p/13457411.html
Copyright © 2011-2022 走看看