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>
  • 相关阅读:
    MySQL 调优 —— Using filesort
    The superclass &quot;javax.servlet.http.HttpServlet&quot; was not found on the Java Build Path
    JMS解决系统间通信问题
    LinkedList,ArrayList末尾插入谁效率高?
    C#学习笔记二:C#程序结构
    C#学习笔记一:C#开发环境的设置
    "NetworkError: 500 Internal Server Error
    JSON数据与JavaScript对象转换
    在使用Ibatis查询数据返回时,报如下错误:java ibatis The error happened while setting a property on the result object
    The APR based Apache Tomcat Native library
  • 原文地址:https://www.cnblogs.com/JasperZhao/p/13457411.html
Copyright © 2011-2022 走看看