dom4j解析XML的基本用法

1. 需要的包:dom4j-1.4/dom4j.jar

2. 用到的类:import org.dom4j.Document;
       import org.dom4j.DocumentHelper;
       import org.dom4j.Element;
       import org.dom4j.io.XMLWriter;
       import org.dom4j.DocumentException;
       import org.dom4j.io.SAXReader;

3. 基本操作:
      创建文档: Document document = DocumentHelper.createDocument();
      创建根节点:Element catalogElement = document.addElement("catalog");
      添加注释: catalogElement.addComment("注释");
      处理指令:
            catalogElement.addProcessingInstruction("target","text");
      增加子节点:Element journalElement = catalogElement.addElement("journal");
      给节点添加属性:journalElement.addAttribute("title", "值");
      设置节点中的文本:journalElement.setText("值");
      添加文档类型:document.addDocType("catalog", null,"file://c:/Dtds/catalog.dtd ");
     
      创建 xml 文件:
      XMLWriter output = new XMLWriter(
              new FileWriter( new File("c:/catalog/catalog.xml") ));
          output.write( document );
          output.close();
         
         
          加载 xml 文件:
         
        SAXReader saxReader = new SAXReader(); //SAXReader 包含在 org.dom4j.io 包中。
        Document document = saxReader.read(new File("c:/catalog/catalog.xml"));

        或者读取字节数组

        Document document = reader.read(new ByteArrayInputStream(string.getBytes("UTF-8")));
       
        使用 XPath 表达式从 article 元素中获得 level 节点列表
        如果 level 属性值是“Intermediate”则改为“Introductory”。
        List list = document.selectNodes("//article/@level " );
          Iterator iter=list.iterator();
            while(iter.hasNext()){
                Attribute attribute=(Attribute)iter.next();
                   if(attribute.getValue().equals("Intermediate"))
                     attribute.setValue("Introductory");
           }

       获取某节点的子节点    
       Iterator iterator=element.elementIterator("title");

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值