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

作者:阳光岛主 时间:2022-06-15 17:08:51 

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的效果图:
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类】

来源:http://blog.csdn.net/sunboy_2050/article/details/7521605

标签:android,dom4j,xml
0
投稿

猜你喜欢

  • C#实现通过winmm.dll控制声音播放的方法

    2022-12-02 06:35:17
  • Java操作Redis详细介绍

    2023-07-27 06:53:04
  • Java多态和实现接口的类的对象赋值给接口引用的方法(推荐)

    2023-11-26 11:59:41
  • 全面总结java IO体系

    2023-05-16 13:19:12
  • Android编程中的消息机制实例详解

    2022-11-14 06:50:05
  • Java concurrency线程池之线程池原理(二)_动力节点Java学院整理

    2023-11-28 23:43:18
  • Android开发应用第一步 安装及配置模拟器Genymotion

    2023-05-25 11:18:09
  • C#条件拼接Expression<Func<T, bool>>的使用

    2023-07-11 22:29:18
  • Springboot实现阿里云通信短信服务有关短信验证码的发送功能

    2022-07-24 15:36:53
  • Android 使用 Scroller 实现平滑滚动功能的示例代码

    2022-01-20 22:49:35
  • 验证本机的excel版本的C#代码

    2021-11-01 07:13:20
  • Java设计模式之工厂模式分析【简单工厂、工厂方法、抽象工厂】

    2021-07-07 21:11:57
  • Android WebView 常见问题及处理方案

    2023-04-13 04:11:57
  • SpringBoot项目集成日志的实现方法

    2023-06-02 23:00:23
  • Android SeekBar实现平滑滚动

    2022-01-21 10:51:24
  • java转树形结构工具类详解

    2021-07-26 04:00:08
  • 详解springmvc控制登录用户session失效后跳转登录页面

    2021-12-08 19:36:40
  • Gradle修改本地仓库的位置方法实现

    2022-01-17 21:25:52
  • Springboot笔记之热部署及不生效的解决方案

    2023-11-03 02:40:00
  • 解决@RequestBody搭配@Data的大坑

    2022-08-29 18:25:35
  • asp之家 软件编程 m.aspxhome.com