欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android 创建与解析XML(五)——详解Dom4j方式

程序员文章站 2024-02-29 14:59:34
1、dom4j概述 dom4j is an easy to use, open source library for working with xml, xpath an...

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.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的效果图:
Android 创建与解析XML(五)——详解Dom4j方式

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(); 
} 

运行结果:
Android 创建与解析XML(五)——详解Dom4j方式

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(); 
} 

运行结果:
Android 创建与解析XML(五)——详解Dom4j方式

解析二:选择性解析(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.

运行结果:
Android 创建与解析XML(五)——详解Dom4j方式

4、person类

请参见前面博客 android 创建与解析xml(二)—— dom方式 【4、person类】

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。