dom4j学习总结(一)

(一)创建Document的基本操作

/**
  * xml基本操作
  */
 public void BaseOperation(){
  //创建一个document
  Document document=DocumentHelper.createDocument();
  //创建根结点
  Element root=document.addElement("root");
  //为根结点添加一个book节点
  Element book1=root.addElement("book");
  //为book1添加属性type
  book1.addAttribute("type","science");
  //为book1添加name子节点
  Element name1=book1.addElement("Name");
  //并设置其name为"Java"
  name1.setText("Java");
  //为book1创建一个price节点,并设其价格为100
  book1.addElement("price").setText("100");
  
  //为根结点添加第二个book节点,并设置该book节点的type属性
  Element book2=root.addElement("book").addAttribute("type","science");
  //为book1添加name子节点
  Element name2=book2.addElement("Name");
  //并设置其name为"Oracle"
  name2.setText("Oracle");
  //为book1创建一个price节点,并设其价格为200
  book2.addElement("price").setText("200");
  
  //输出xml
  System.out.println(document.asXML());
 }

调用BaseOperation,输出结果为:

<?xml version="1.0" encoding="UTF-8"?>
<root>
 <book type="science">
  <Name>Java</Name>
  <price>100</price>
 </book>
 <book type="science">
  <Name>Oracle</Name>
  <price>200</price>
 </book>
</root>

(二)根据一个符合Document格式的字符串来生成一个Document

/**将字符串转化为Document
  * @param str  输入的字符串
  * @return  生成的document
  * @throws DocumentException
  */
 public Document parserStrtoDocument(String str) throws DocumentException{
  Document document=DocumentHelper.parseText(str);
  return document;
 }

调用示例:

String str="<root><book type='science'><Name>Java</Name><price>100</price></book></root>";

Document document = parserStrtoDocument(str);
  System.out.println(document.asXML());

输出结果为:

<?xml version="1.0" encoding="UTF-8"?>
<root>
 <book type="science">
  <Name>Java</Name>
  <price>100</price>
 </book>
</root>

(三)取得xml节点属性的基本方法

/**
  * 取得xml的节点和属性的值
  * @throws DocumentException 
  */
 public void getBaseInfofromDocument() throws DocumentException{
  String str="<root><book type='science'><Name>Java</Name><price>100</price></book></root>";
  //生成一个Document
  Document document = DocumentHelper.parseText(str);
  //取得根结点
  Element root=document.getRootElement();
  //取得book节点
  Element book=root.element("book");
  //取得book节点的type属性的值
  String type=book.attributeValue("type");
  //取得Name节点
  Element name=book.element("Name");
  //取得书名
  String bookname=name.getText();
  //取得书的价钱
  int price=Integer.parseInt(book.element("price").getText());
  
  //输出书目信息
  System.out.println("书名:"+bookname);
  System.out.println("所属类别:"+type);
  System.out.println("价格:"+price);
 }

调用getBaseInfofromDocument,输出结果为:

书名:Java
所属类别:science
价格:100

(四)利用迭代,xpath取得节点及其属性值

/**利用迭代,xpath取得xml的节点及其属性值
  * @throws DocumentException
  */
 public void getComplexInfofromDocument() throws DocumentException{

String str="<root><book type='science'><Name>Java</Name><price>100</price></book>"
   +"<book type='science'><Name>Oracle</Name><price>120</price></book>"
   +"<book type='society'><Name>Society security</Name><price>130</price></book>"
   +"<author><name>chb</name></author></root>";
  //生成一个Document
  Document document = DocumentHelper.parseText(str);
  
  //提取类型为"society"的书
  //此处需要添加支持xpath的jar包,详细见备注
  Element society_book=(Element)document.selectSingleNode("/root/book[@type='society']");
  System.out.println(society_book.asXML());
  
  //提取价格节点的列表
  System.out.println("-----------价格列表-------------");
  List price=document.selectNodes("//price");
  for(int i=0;i<price.size();i++){
   Element elem_price=(Element)price.get(i);
   System.out.println(elem_price.getText());
  }
  
  //循环根结点下的所有节点,若当前节点为book,则输出这本书的详细信息
  System.out.println("-------------书目详情------------");
  System.out.println("书名/t/t类别/t/t价格");
  Element root=document.getRootElement();
  Iterator iterator=root.elementIterator();
  while(iterator.hasNext()){
   Element element=(Element)iterator.next();
   if(element.getName().equals("book")){
    System.out.print(element.element("Name").getText()+"/t");
    System.out.print(element.attributeValue("type")+"/t/t");
    System.out.print(element.element("price").getText()+"/n");
   }
  }

//查找作者姓名
  Element author=(Element)document.selectSingleNode("//author");
  System.out.println("---------"+author.element("name").getText()+"----------");
  //提取作者的所有书目名称
  Iterator iterator_book=root.elementIterator("book");  
  while(iterator_book.hasNext()){
   Element book=(Element)iterator_book.next();
   System.out.print(book.element("Name").getText()+"/t");
  }
  
  //属性迭代
  System.out.println("/n-------属性迭代--------");
  String str1="<book type='science' name='Java' price='100'/>";
  Document document1=DocumentHelper.parseText(str1);
  //开始迭代
  Iterator iterator_attribute=document1.getRootElement().attributeIterator();
  while(iterator_attribute.hasNext()){
   //提取当前属性
   Attribute attribute=(Attribute)iterator_attribute.next();
   System.out.println(attribute.getName()+":"+attribute.getValue());
  }
 }

调用getComplexInfofromDocument,输出结果为:

<book type="society"><Name>Society security</Name><price>130</price></book>
-----------价格列表-------------
100
120
130
-------------书目详情------------
书名  类别  价格
Java science  100
Oracle science  120
Society security society  130
---------chb----------
Java Oracle Society security 
-------属性迭代--------
type:science
name:Java
price:100

备注:调用该方法之前,应该先向工程中添加支持xpath的jar包,否则,会出现以下错误:

java.lang.NoClassDefFoundError: org/jaxen/JaxenException
 at org.dom4j.DocumentFactory.createXPath(DocumentFactory.java:230)
 at org.dom4j.tree.AbstractNode.createXPath(AbstractNode.java:207)
 at org.dom4j.tree.AbstractNode.selectSingleNode(AbstractNode.java:183)
 at xml_chb.dom4j_chb.getComplexInfofromDocument(dom4j_chb.java:82)
 at xml_chb.dom4j_chb.main(dom4j_chb.java:92)
Exception in thread "main"

只需要引入jaxen包就行了,我使用的是hibernate包中的jaxen-1.1-beta-7.jar包。

dom4j学习总结(一)的更多相关文章

  1. dom4j学习

    在使用xml读写的过程中,用到了dom4j,也算是一个比较主流的xml包了,在使用的过程中,将学习经历记录一下,以后查阅也比较方便. 首先是在pom中添加依赖,在Maven的中心库搜索后选择了该包: ...

  2. dom4j 学习总结

    Dom4j is an easy to use, open source library for working with XML, XPath and XSLT on the Java platfo ...

  3. dom4J 学习

    Java给我们提供了标准的W3C接口实现,已完成对XML的处理.主要有两大类,分别是DOM操作,SAX解析.DOM可以将XML加载到内存中,对XML进行方便的增删查改.由于是将整个XML都加载到内存中 ...

  4. Dom4j 学习笔记

    dom4j 是一种解析 XML 文档的开放源代码 XML 框架.dom4j下载地址 本文主要记载了一些简单的使用方法. 一.xml文件的解析 dom4j既可以解析普通的xml文件,也可以解析一个Inp ...

  5. Dom4j学习笔记

    一.Loading XML Data 以下代码从File中或一个URL中读取一个XML文件,并产生一个Document对象.一个Document对象表示了内存中的一棵XML树,可以在这个XML树中进行 ...

  6. dom4j处理带命名空间的XML-使用XPath(转)

    dom4j处理带命名空间的XML-使用XPath 博客分类: XML   XPath 是一门在 XML 文档中查找信息的语言.XPath 可用来在 XML 文档中对元素和属性进行遍历. XPath 使 ...

  7. XML学习笔记(2)--dom4j操作XML

    1. 介绍(四种方式的比较这部分转载自:http://www.blogjava.net/xcp/archive/2010/02/12/312617.html) 1)DOM(JAXP Crimson解析 ...

  8. java学习笔记DOM4J解析(7)

    DOM4J即Document Object Model for Java使用java技术以文档方式解析XML数据的模型. DOM4J是开源组织提供的一个免费的.强大的XML解析工具,如果开发者需要在项 ...

  9. JavaWeb学习笔记——DOM4J

    下载的地址为:http://www.dom4j.org/dom4j-1.6.1/ import java.io.File; import java.io.FileOutputStream; impor ...

随机推荐

  1. Spring 学习记录4 ResourceLoader

    ResourceLoader Spring的ApplicationContext继承了ResourceLoader接口.这个接口主要就是可以加载各种resource.. 接口还是比较简单的: /* * ...

  2. 重构--去除丑陋的switch语句

    最近几天,在进行重构的时候,遇到了一个极其丑陋的代码(自己写的 /捂脸  当时时间紧,于是....),今天去重构的时候无论如何也想不出方法,去除这个丑陋的switch语句 ,于是写篇博客,让自己记住这 ...

  3. avalon最佳实践

    最近从angular的QQ群与新浪微博拉了许多人来用我的avalon,成为第一批登上方舟,脱离DOM苦海的人.短短三个月内,5群的朋友也搞出几个切实实行的案例了.为应对粉丝们高益高涨的热情,遂放出此文 ...

  4. Javascript —— 有向图广度优先搜索

    用Javascript实现有向图的广度优先搜索 刚好遇到一个需求,对于一个有向图,指定一个节点 i 作为起点,输出从 i 出发,可以到达的所有节点,也就是图中以 i 作为起点的子连通片,思考了一下,可 ...

  5. Quartz_2_简单编程式任务调度使用(CronTrigger)

    第二个要介绍的任务调度器中的触发器是 CronTrigger ,相比较 SimpleTrigger 来说,CronTrigger 相对灵活,对于复杂的业务需求来说,更加的实用.要在使用 CronTri ...

  6. linux shell脚本编程笔记(一): 构建基本脚本

    1. echo -n str        打印不换行 2. 反引号来圈住命令传入变量 eg: 生成日志文件: #!/bin/bash today=`date +%y%m%d` ls /usr/bin ...

  7. 【LA11248 训练指南】网络扩容【最大流】

    题意: 给定一个有向网络,每条边均有一个容量.问是否存在一个从点1到点N,流量为C的流.如果不存在,是否可以恰好修改一条弧的容量,使得存在这样的流? 分析: 先跑一遍最大流,如果最大流大于等于C,则输 ...

  8. SUSE制作ISO源

    These commands have been tested on openSUSE 11. First create a directory where you will store your I ...

  9. 9-queue

    在C++中只要#include<queue>即可使用队列类,其中在面试或笔试中常用的成员函数如下(按照最常用到不常用的顺序) 1. push 2. pop 3. size 4. empty ...

  10. ProxyPattern(23种设计模式之一)

    设计模式六大原则(1):单一职责原则 设计模式六大原则(2):里氏替换原则 设计模式六大原则(3):依赖倒置原则 设计模式六大原则(4):接口隔离原则 设计模式六大原则(5):迪米特法则 设计模式六大 ...