• 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>
  • 相关阅读:
    HDU2438:Turn the corner(三分)
    XTU1267:Highway(LCA+树的直径)
    HDU6024:Building Shops(DP)
    “玲珑杯”ACM比赛 Round #13 B -- 我也不是B(二分排序)
    XTU1266:Parentheses(贪心+优先队列)
    Educational Codeforces Round 21 D
    Educational Codeforces Round 21E selling souvenirs (dp)
    EOJ3247:铁路修复计划
    关于工厂模式的 个人理解
    设计模式之 工厂方法
  • 原文地址:https://www.cnblogs.com/JasperZhao/p/13457411.html
Copyright © 2020-2023  润新知