Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android 創建與解析XML(五)——詳解Dom4j方式

Android 創建與解析XML(五)——詳解Dom4j方式

編輯:關於Android編程

1、Dom4j概述

dom4j is an easy to use, open source library for working with XML, XPath and XSLT on the Java platform using the Java Collections Framework and with full support for DOM, SAX and JAXP.

dom4j官方網址:dom4j 

dom4j源碼下載:dom4j download

本示例中,需要導入dom4j.jar包,才能引用dom4j相關類,dom4j源碼和jar包,請見本示例【源碼下載】或訪問 dom4j

org.dom4j包,不僅包含創建xml的構建器類DocumentHelper、Element,而且還包含解析xml的解析器SAXReader、Element,包含類如下:

org.dom4j

  • org.dom4j.DocumentHelper;
  • org.dom4j.Element;
  • org.dom4j.io.SAXReader;
  • org.dom4j.io.XMLWriter;
  • org.dom4j.DocumentException;

創建和解析xml的效果圖:

2、Dom4j 創建 XML

Dom4j,創建xml主要用到了org.dom4j.DocumentHelper、org.dom4j.Document、org.dom4j.io.OutputFormat、org.dom4j.io.XMLWriter

首先,DocumentHelper.createDocument(),創建 org.dom4j.Document 的實例 doc

接著,通過doc,設置xml屬性doc.setXMLEncoding("utf-8")、doc.addElement("root")根節點,以及子節點等

然後,定義xml格式並輸出,new XMLWriter(xmlWriter, outputFormat)

/** Dom4j方式,創建 XML */ 
public String dom4jXMLCreate(){ 
  StringWriter xmlWriter = new StringWriter(); 
 
  Person []persons = new Person[3];    // 創建節點Person對象 
  persons[0] = new Person(1, "sunboy_2050", "http://blogcsdnnet/sunboy_2050"); 
  persons[1] = new Person(2, "baidu", "http://wwwbaiducom"); 
  persons[2] = new Person(3, "google", "http://wwwgooglecom"); 
   
  try { 
    orgdom4jDocument doc = DocumentHelpercreateDocument(); 
     
    docsetXMLEncoding("utf-8"); 
     
    orgdom4jElement eleRoot = docaddElement("root"); 
    eleRootaddAttribute("author", "homer"); 
    eleRootaddAttribute("date", "2012-04-25"); 
    eleRootaddComment("dom4j test"); 
     
    int personsLen = personslength; 
    for(int i=0; i<personsLen; i++){ 
       
      Element elePerson = eleRootaddElement("person");  // 創建person節點,引用類為 orgdom4jElement 
       
      Element eleId = elePersonaddElement("id"); 
      eleIdaddText(persons[i]getId()+""); 
       
      Element eleName = elePersonaddElement("name"); 
      eleNameaddText(persons[i]getName()); 
       
      Element eleBlog = elePersonaddElement("blog"); 
      eleBlogaddText(persons[i]getBlog()); 
    } 
 
    orgdom4jioOutputFormat outputFormat = new orgdom4jioOutputFormat();  // 設置xml輸出格式 
    outputFormatsetEncoding("utf-8"); 
    outputFormatsetIndent(false); 
    outputFormatsetNewlines(true); 
    outputFormatsetTrimText(true); 
     
    orgdom4jioXMLWriter output = new XMLWriter(xmlWriter, outputFormat);   // 保存xml 
    outputwrite(doc); 
    outputclose(); 
  } catch (Exception e) { 
    eprintStackTrace(); 
  } 
   
  savedXML(fileName, xmlWritertoString()); 
  return xmlWritertoString(); 
} 

運行結果:

3、Dom4j 解析 XML

Dom4j,解析xml主要用到了org.dom4j.io.SAXReader、org.dom4j.Document、doc.getRootElement(),以及ele.getName()、ele.getText()等

首先,創建SAXReader的實例reader,讀入xml字節流 reader.read(is)

接著,通過doc.getRootElement()得到root根節點,利用迭代器取得root下一級的子節點eleRoot.elementIterator()等

然後,得到解析的xml內容xmlWriter.append(xmlHeader)、xmlWriter.append(personsList.get(i).toString())

解析一:標准解析(Iterator 迭代)

/** Dom4j方式,解析 XML */ 
public String dom4jXMLResolve(){ 
  StringWriter xmlWriter = new StringWriter(); 
   
  InputStream is = readXML(fileName); 
  try { 
    SAXReader reader = new SAXReader(); 
    orgdom4jDocument doc = readerread(is); 
 
    List<Person> personsList = null; 
    Person person = null; 
    StringBuffer xmlHeader = new StringBuffer(); 
     
     
    Element eleRoot = docgetRootElement();   // 獲得root根節點,引用類為 orgdom4jElement 
    String attrAuthor = eleRootattributeValue("author"); 
    String attrDate = eleRootattributeValue("date"); 
    xmlHeaderappend("root")append("\t\t"); 
    xmlHeaderappend(attrAuthor)append("\t"); 
    xmlHeaderappend(attrDate)append("\n"); 
    personsList = new ArrayList<Person>(); 
     
    // 獲取root子節點,即person 
    Iterator<Element> iter = eleRootelementIterator(); 
    for(; iterhasNext(); ) { 
      Element elePerson = (Element)iternext(); 
       
      if("person"equals(elePersongetName())){ 
        person = new Person(); 
         
        // 獲取person子節點,即id、name、blog 
        Iterator<Element> innerIter = elePersonelementIterator(); 
        for(; innerIterhasNext();) { 
          Element ele = (Element)innerIternext(); 
           
          if("id"equals(elegetName())) { 
            String id = elegetText(); 
            personsetId(IntegerparseInt(id)); 
          } else if("name"equals(elegetName())) { 
            String name = elegetText(); 
            personsetName(name); 
          } else if("blog"equals(elegetName())) { 
            String blog = elegetText(); 
            personsetBlog(blog); 
          } 
        } 
         
        personsListadd(person); 
        person = null; 
      } 
    } 
     
    xmlWriterappend(xmlHeader); 
    int personsLen = personsListsize(); 
    for(int i=0; i<personsLen; i++) { 
      xmlWriterappend(personsListget(i)toString()); 
    } 
     
  } catch (DocumentException e) { 
    eprintStackTrace(); 
  } catch (Exception e) { 
    eprintStackTrace(); 
  } 
   
  return xmlWritertoString(); 
} 

運行結果:

解析二:選擇性解析(XPath路徑)

Dom4j+XPath,選擇性只解析id,doc.selectNodes("//root//person//id")

/** Dom4j方式,解析 XML(方式二) */ 
public String dom4jXMLResolve2(){ 
  StringWriter xmlWriter = new StringWriter(); 
   
  InputStream is = readXML(fileName); 
  try { 
    orgdom4jioSAXReader reader = new orgdom4jioSAXReader(); 
    orgdom4jDocument doc = readerread(is); 
 
    List<Person> personsList = null; 
    Person person = null; 
    StringBuffer xmlHeader = new StringBuffer(); 
     
     
    Element eleRoot = docgetRootElement();   // 獲得root根節點,引用類為 orgdom4jElement 
    String attrAuthor = eleRootattributeValue("author"); 
    String attrDate = eleRootattributeValue("date"); 
    xmlHeaderappend("root")append("\t\t"); 
    xmlHeaderappend(attrAuthor)append("\t"); 
    xmlHeaderappend(attrDate)append("\n"); 
    personsList = new ArrayList<Person>(); 
     
    @SuppressWarnings("unchecked") 
    List<Element> idList = (List<Element>) docselectNodes("//root//person//id");  // 選擇性獲取全部id 
    Iterator<Element> idIter = idListiterator(); 
    while(idIterhasNext()){ 
      person = new Person(); 
       
      Element idEle = (Element)idIternext(); 
      String id = idElegetText(); 
      personsetId(IntegerparseInt(id)); 
       
      personsListadd(person); 
    } 
 
    xmlWriterappend(xmlHeader); 
    int personsLen = personsListsize(); 
    for(int i=0; i<personsLen; i++) { 
      xmlWriterappend("id = ")append(personsListget(i)getId()+"")append("\n"); 
    } 
     
  } catch (DocumentException e) { 
    eprintStackTrace(); 
  } catch (Exception e) { 
    eprintStackTrace(); 
  } 
   
  return xmlWritertoString(); 
} 

注:借助 XPath 解析 XML 時,需要導入 jaxen;

Jaxen is an open source XPath library written in Java. It is adaptable to many different object models, including DOM, XOM, dom4j, and JDOM. Is it also possible to write adapters that treat non-XML trees such as compiled Java byte code or Java beans as XML, thus enabling you to query these trees with XPath too.

運行結果:

4、Person類

請參見前面博客 Android 創建與解析XML(二)—— Dom方式 【4、Person類】

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持本站。

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved