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>
  • 相关阅读:
    当期所得税费用总额
    所得税净利润算法
    [AGC028B]Removing Blocks 概率与期望
    bzoj 4319: cerc2008 Suffix reconstruction 贪心
    bzoj 2430: [Poi2003]Chocolate 贪心
    BZOJ 2839: 集合计数 广义容斥
    luogu 5505 [JSOI2011]分特产 广义容斥
    CF504E Misha and LCP on Tree 后缀自动机+树链剖分+倍增
    CF798D Mike and distribution 贪心
    CF707D Persistent Bookcase 可持久化线段树
  • 原文地址:https://www.cnblogs.com/JasperZhao/p/13457411.html
Copyright © 2011-2022 走看看