Dom4j解析Xml文件,Dom4j创建Xml文件

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

蕃薯耀 2016年3月1日 10:54:34 星期二

http://fanshuyao.iteye.com/

一、引入Jar包

dom4j-1.6.1.jar

二、详细代码

package com.lqy.dom4j;import java.io.File;
import java.io.FileWriter;
import java.util.Iterator;import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;public class Dom4jTest {public static void main(String[] args) throws Exception {//createXml();//createXml2();readXml1();}private static void createXml() throws Exception{Document document = DocumentHelper.createDocument();Element rootElement = document.addElement("students");Element studentElement = rootElement.addElement("student");studentElement.addAttribute("id", "s001");studentElement.addAttribute("xx", "xx001");studentElement.addElement("name").addText("张三");studentElement.addElement("age").addText("20");Element studentElement1 = rootElement.addElement("student");studentElement1.addAttribute("id", "s002");studentElement1.addAttribute("xx", "xx002");studentElement1.addElement("name").addText("李四");studentElement1.addElement("age").addText("21");XMLWriter xmlWriter = new XMLWriter(new FileWriter("src/student.xml"));xmlWriter.write(rootElement);xmlWriter.close();System.out.println("执行完成了!");}private static void createXml2() throws Exception{Document document = DocumentHelper.createDocument();Element rootElement = document.addElement("students");Element stu1 = rootElement.addElement("student");stu1.addAttribute("id", "s001");stu1.addAttribute("xx", "xx001");stu1.addElement("name").addText("张三");stu1.addElement("age").addText("20");Element stu2 = rootElement.addElement("student");stu2.addAttribute("id", "s002");stu2.addAttribute("xx", "xx002");stu2.addElement("name").addText("李四");stu2.addElement("age").addText("21");OutputFormat outputFormat = OutputFormat.createPrettyPrint();XMLWriter xmlWriter = new XMLWriter( System.out, outputFormat);xmlWriter.write( document );xmlWriter.close();System.out.println("执行完成了!");}private static void readXml1() throws Exception{SAXReader saxReader = new SAXReader();Document document = saxReader.read(new File("src/student.xml"));if(document != null){Element root = document.getRootElement();if(root != null){Iterator<Element> iterator = root.elementIterator();while(iterator.hasNext()){Element e = iterator.next();System.out.println("学生信息:");System.out.println("学生id:"+e.attributeValue("id"));System.out.println("学生xx:"+e.attributeValue("xx"));System.out.println("学生姓名:"+e.elementText("name"));System.out.println("学生年龄:"+e.elementText("age"));System.out.println("==========================");}}}}
}

三、官网文档:

Parsing XML

One of the first things you'll probably want to do is to parse an XML document of some kind. This is easy to do in dom4j. The following code demonstrates how to this.

import java.net.URL;import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;public class Foo {public Document parse(URL url) throws DocumentException {SAXReader reader = new SAXReader();Document document = reader.read(url);return document;}
}

Using Iterators

A document can be navigated using a variety of methods that return standard Java Iterators. For example

    public void bar(Document document) throws DocumentException {Element root = document.getRootElement();// iterate through child elements of rootfor ( Iterator i = root.elementIterator(); i.hasNext(); ) {Element element = (Element) i.next();// do something}// iterate through child elements of root with element name "foo"for ( Iterator i = root.elementIterator( "foo" ); i.hasNext(); ) {Element foo = (Element) i.next();// do something}// iterate through attributes of root for ( Iterator i = root.attributeIterator(); i.hasNext(); ) {Attribute attribute = (Attribute) i.next();// do something}}

Powerful Navigation with XPath

In dom4j XPath expressions can be evaluated on the Document or on any Node in the tree (such as Attribute, Element or ProcessingInstruction). This allows complex navigation throughout the document with a single line of code. For example.

    public void bar(Document document) {List list = document.selectNodes( "//foo/bar" );Node node = document.selectSingleNode( "//foo/bar/author" );String name = node.valueOf( "@name" );}

For example if you wish to find all the hypertext links in an XHTML document the following code would do the trick.

    public void findLinks(Document document) throws DocumentException {List list = document.selectNodes( "//a/@href" );for (Iterator iter = list.iterator(); iter.hasNext(); ) {Attribute attribute = (Attribute) iter.next();String url = attribute.getValue();}}

If you need any help learning the XPath language we highly recommend the Zvon tutorial which allows you to learn by example.

Fast Looping

If you ever have to walk a large XML document tree then for performance we recommend you use the fast looping method which avoids the cost of creating an Iterator object for each loop. For example

    public void treeWalk(Document document) {treeWalk( document.getRootElement() );}public void treeWalk(Element element) {for ( int i = 0, size = element.nodeCount(); i < size; i++ ) {Node node = element.node(i);if ( node instanceof Element ) {treeWalk( (Element) node );}else {// do something....}}}

Creating a new XML document

Often in dom4j you will need to create a new document from scratch. Here's an example of doing that.

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;public class Foo {public Document createDocument() {Document document = DocumentHelper.createDocument();Element root = document.addElement( "root" );Element author1 = root.addElement( "author" ).addAttribute( "name", "James" ).addAttribute( "location", "UK" ).addText( "James Strachan" );Element author2 = root.addElement( "author" ).addAttribute( "name", "Bob" ).addAttribute( "location", "US" ).addText( "Bob McWhirter" );return document;}
}

Writing a document to a file

A quick and easy way to write a Document (or any Node) to a Writer is via the write() method.

  FileWriter out = new FileWriter( "foo.xml" );document.write( out );

If you want to be able to change the format of the output, such as pretty printing or a compact format, or you want to be able to work with Writer objects or OutputStream objects as the destination, then you can use the XMLWriter class.

import org.dom4j.Document;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;public class Foo {public void write(Document document) throws IOException {// lets write to a fileXMLWriter writer = new XMLWriter(new FileWriter( "output.xml" ));writer.write( document );writer.close();// Pretty print the document to System.outOutputFormat format = OutputFormat.createPrettyPrint();writer = new XMLWriter( System.out, format );writer.write( document );// Compact format to System.outformat = OutputFormat.createCompactFormat();writer = new XMLWriter( System.out, format );writer.write( document );}
}

Converting to and from Strings

If you have a reference to a Document or any other Node such as an Attribute or Element, you can turn it into the default XML text via the asXML() method.

        Document document = ...;String text = document.asXML();

If you have some XML as a String you can parse it back into a Document again using the helper method DocumentHelper.parseText()

        String text = "<person> <name>James</name> </person>";Document document = DocumentHelper.parseText(text);

Styling a Document with XSLT

Applying XSLT on a Document is quite straightforward using the JAXP API from Sun. This allows you to work against any XSLT engine such as Xalan or SAXON. Here is an example of using JAXP to create a transformer and then applying it to a Document.

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;import org.dom4j.Document;
import org.dom4j.io.DocumentResult;
import org.dom4j.io.DocumentSource;public class Foo {public Document styleDocument(Document document, String stylesheet) throws Exception {// load the transformer using JAXPTransformerFactory factory = TransformerFactory.newInstance();Transformer transformer = factory.newTransformer( new StreamSource( stylesheet ) );// now lets style the given documentDocumentSource source = new DocumentSource( document );DocumentResult result = new DocumentResult();transformer.transform( source, result );// return the transformed documentDocument transformedDoc = result.getDocument();return transformedDoc;}
}

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

蕃薯耀 2016年3月1日 10:54:34 星期二

http://fanshuyao.iteye.com/

Dom4j解析Xml文件,Dom4j创建Xml文件相关推荐

  1. hadoop HDFS的文件夹创建、文件上传、文件下载、文件夹删除,文件更名、文件详细信息、文件类型判断(文件夹或者文件)

    摘要: 本篇文章主要介绍的是hadoop hdfs的基础api的使用.包括Windows端依赖配置,Maven依赖配置.最后就是进行实际的操作,包括:获取远程hadoop hdfs连接,并对其进行的一 ...

  2. python读取nc文件转成img_使用python的netCDF4库读取.nc文件 和 创建.nc文件[转]

    使用python netCDF4库读取.nc文件 和 创建.nc文件 1. 介绍 .nc(network Common Data Format)文件是气象上常用的数据格式,python上读取.nc使用 ...

  3. oracle 创建日志文件,oracle创建日志文件

    一团网资讯 一团资讯 > oracle > oracle创建日志文件 oracle创建日志文件 2018-04-14 15:39:48     发布者:来源网络 创建日志文件的语法如下: ...

  4. python学习(二) ElementTree解析、读写、创建xml文件

    python学习(二) 读写xml文件 1.xml格式 将其存储为sample.xml  Tag:使用<>包围的部分  Element:被Tag包围的部分,例如22中的22  Attrib ...

  5. 使用dom4j解析xml_使用dom4j解析XML

    使用dom4j解析xml dom4j API下载包括用于解析XML文档的工具. 在本文中,将使用解析器创建示例XML文档. 清单1显示了示例XML文档catalog.xml. 清单1.示例XML文档( ...

  6. python读xml文件生成.h头文件_Python创建xml文件示例

    Python创建xml文件示例 这里有新鲜出炉的 Python 入门,程序狗速度看过来! Python 编程语言 Python 是一种面向对象.解释型计算机程序设计语言,由 Guido van Ros ...

  7. xml操作之创建xml节点

    Xml是一个存放数据的小型数据库文件,这个应用也很广泛,先把数据添加保存到xml中,然后在读取出来,今天就来看看如何创建xml节点并添加数据,代码如下:   protected void Insert ...

  8. html怎么建立css文件,怎么创建css文件

    如何新建css文件文件→新建→css文件,建好之后,在html文档中将其引入: 希望对你有帮助,望喜欢. css怎么建立外部样式表? 建立外部样式表很简单,就在html的head里写 至于你上边说的一 ...

  9. hdf5文件和csv的区别_使用HDF5文件并创建CSV文件

    hdf5文件和csv的区别 In my last article, I discussed the steps to download NASA data from GES DISC. The dat ...

  10. dbf文件怎么创建_DBC文件到底是个啥

    本文首发自公众号"汽车技术馆" 在之前的一篇文章中给大家分享了一些CAN的基本知识,比如CAN通讯是个啥,CAN通讯的机制以及CAN通讯的帧结构等等,相信读过这篇文章的朋友应该都有 ...

最新文章

  1. 构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(12)-系统日志和异常的处理②...
  2. Google、Intel、Uber等巨头如何布局AI?听听他们自己人怎么说
  3. 如何在 Windows 中检查计算机正常运行时间
  4. python将一组数分成每3个一组
  5. mysql 5.7.15 安装_mysql 5.7.15 安装配置方法图文教程
  6. linux下mysql的备份_Linux下MySQL的备份与还原
  7. ES6-18/19 异步的开端-promise
  8. ios开发 访问mysql_iOS开发实战-时光记账Demo 网络版
  9. linux函数入参个数限制,PowerShell函数中限制数组参数个数的例子
  10. 电阻屏和电容屏的区别
  11. iPhone~iPhone14屏幕尺寸和分辨率的相关知识 ( DPI vs PPI pt vs px)
  12. 魔方机器人机械部分_通过强化学习解决第2部分的魔方
  13. WebP是什么格式?如何免费批量转换JPEG
  14. 为什么学校计算机没有声音,电脑为什么没声音,教您电脑为什么没声音
  15. 计算机大二学生个人总结报告,计算机学生大二第二学期自我总结计划自我总结计划.doc...
  16. iOS之UITableView组头组尾视图/标题悬停
  17. Quartus | FPGA开发工具(Inter系列芯片)
  18. 强网杯-强网先锋辅助
  19. 杰理之硅麦驻体麦区别
  20. 2021年中国体育彩票行业市场现状分析,体彩销售额同比增长21.9%「图」

热门文章

  1. python中lambda的用法
  2. YApi--使用YApi的目的
  3. mysql和oracle数据库兼容性_oracle数据库兼容mysql的差异写法
  4. 1 2014年12月电大远程网络教育计算机统考 最 新 题 库,2014年12月份电大远程网络教育计算机应用基础统考题库试卷6...
  5. 简述工业机器人示教再现的一般步骤_基于激光焊缝跟踪传感器的工业机器人焊缝跟踪系统的应用焊接寻位...
  6. 同名字的数值求和插入行_SUM求和函数的运用,这些EXCEL表格技能你必须知道,让你事半功倍...
  7. java p=x,Java-Tutorial/20、javac和javap.md at master · allenchenx/Java-Tutorial · GitHub
  8. arm linux 蜂鸣器qt,Qt 程序中使用蜂鸣器 ioctl()
  9. Java项目课程06:系统实现-数据库
  10. 安卓学习笔记24:常用控件 - 循环器视图