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");

發佈了33 篇原創文章 · 獲贊 0 · 訪問量 1875
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章