亲宝软件园·资讯

展开

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

阳光岛主 人气:0
想了解Android 创建与解析XML(五)——详解Dom4j方式的相关内容吗,阳光岛主在本文为您仔细讲解android dom4j解析xml的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:android,dom4j解析xml,dom4j解析xml,java,dom4j生成xml,下面大家一起来学习吧。

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

创建和解析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类】

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

加载全部内容

相关教程
猜你喜欢
用户评论