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 root
for ( 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 file
XMLWriter writer = new XMLWriter(
new FileWriter( "output.xml" )
);
writer.write( document );
writer.close(); // Pretty print the document to System.out
OutputFormat format = OutputFormat.createPrettyPrint();
writer = new XMLWriter( System.out, format );
writer.write( document ); // Compact format to System.out
format = 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 JAXP
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer(
new StreamSource( stylesheet )
); // now lets style the given document
DocumentSource source = new DocumentSource( document );
DocumentResult result = new DocumentResult();
transformer.transform( source, result ); // return the transformed document
Document transformedDoc = result.getDocument();
return transformedDoc;
}
}

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

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

http://fanshuyao.iteye.com/

Dom4j解析Xml文件,Dom4j创建Xml文件的更多相关文章

  1. solr 6.0 没有schema.xml未自动创建schema文件

    solr 6.0 没有schema.xml未自动创建schema文件 摘要:在之前的Solr版本中(Solr5之前),在创建core的时候,Solr会自动创建好schema.xml,但是在之后的版本中 ...

  2. C#操作XML学习之创建XML文件的同时新建根节点和子节点(多级子节点)

    最近工作中遇到一个问题,要求创建一个XML文件,在创建的时候要初始化该XML文档,同时该文档打开后是XML形式,但是后缀名不是.在网上找了好些资料没找到,只能自己试着弄了一下,没想到成功了,把它记下来 ...

  3. Qt-QML-C++交互实现文件IO系统-后继-读取XML文件和创建XML文件

    在前面两篇中,大致完成了一个文件IO的读和写操作.前面两篇文章链接 http://blog.csdn.net/z609932088/article/details/71488250 http://bl ...

  4. dom4j解析器 基于dom4j的xpath技术 简单工厂设计模式 分层结构设计思想 SAX解析器 DOM编程

    *1 dom4j解析器   1)CRUD的含义:CreateReadUpdateDelete增删查改   2)XML解析器有二类,分别是DOM和SAX(simple Api for xml).     ...

  5. 使用文件流创建File文件和目录以及其他的一些操作

    我们创建文件时可以直接通过File f=new File(path)来创建一个文件对象,然后再通过 f.createNewFile() 就创建出来了一个文件.比如设置 path 为 C:\Users\ ...

  6. 2.6.1 XML配置:创建XML文件

    (1) 工程名右击---New--file  --  newfile窗口中:filename中输入testng.xml testng.xml 文件中打开后,切换到source 标签中.进行编辑. 内容 ...

  7. pycharm新建ini文件或创建ini文件失败

    1.pycharm创建ini格式的文件,没有对应的 ini 文件类型-------需要更新 Ini 2.setting–>marketplace 搜索 Ini ,然后进行安装,重启pycharm ...

  8. android在当前app该文件下创建一个文件夹

    /*********************************************************************  * Author  : Samson  * Date   ...

  9. 关于在Idea 创建Maven项目时,无法在source文件下创建servlet文件问题解决!

    很简单:打开.iml文件,

  10. java使用dom4j解析xml文件

    关于xml的知识,及作用什么的就不说了,直接解释如何使用dom4j解析.假如有如下xml: dom4j解析xml其实很简单,只要你有点java基础,知道xml文件.结合下面的xml文件和java代码, ...

随机推荐

  1. 使用Qt实现简单的图片预览效果 good

    http://www.cnblogs.com/appsucc/archive/2012/02/28/2371506.html Qt之实现工具箱界面程序 http://www.cnblogs.com/a ...

  2. AD域环境的搭建 基于Server 2008 R2

    AD(Active Directory)即活动目录,微软的基础件.微软的很多产品如:Exchange Server,Lync Server,SharePoint Server,Forefront Se ...

  3. haskell Types 和 Typeclasses

    Algebraic Data Types 入门 在前面的章节中,我们谈了一些 Haskell 内置的类型和 Typeclass.而在本章中,我们将学习构造类型和 Typeclass 的方法. 我们已经 ...

  4. WebBrowser控件跨域访问页面内容

    原文出处 :http://blog.csdn.net/nocky/article/details/6056802 源码出处:http://www.codecentrix.com/blog/wnd2do ...

  5. git支持中文

    以前使用git,都要参考这个来进行中文支持 http://blog.csdn.net/son_of_god/article/details/7341928 有一次更新了git之后,发现默认支持了中文[ ...

  6. .NET开发不可错过的25款高效工具

    这些年来,微软的 .NET 开发团队不断在更新升级开发工具,这也提供了一个机会,让我们能对 .NET 系列的开发工具做出不断的评估和规范.以下是我们总结出的一些 .NET 开发不可错过的高效工具. 1 ...

  7. 一起啃PRML - 1.2.1 Probability densities 概率密度

    一起啃PRML - 1.2.1 Probability densities @copyright 转载请注明出处 http://www.cnblogs.com/chxer/ 我们之前一直在讨论“谁取到 ...

  8. Muduo-Base-TimeStamp类

    Muduo的时间戳类. 主要功能: 能够获取当前的时间 能够将当前的时间以string的形式返回 能够获取两个时间戳类的时间差 能够获取当前精确的时间(微秒级) #ifndef TIMESTAMP_H ...

  9. [CODEVS1294]全排列

    题目描述 Description 给出一个n, 请输出n的所有全排列 输入描述 Input Description 读入仅一个整数n   (1<=n<=10) 输出描述 Output De ...

  10. Bzoj 1616: [Usaco2008 Mar]Cow Travelling游荡的奶牛 动态规划

    1616: [Usaco2008 Mar]Cow Travelling游荡的奶牛 Time Limit: 5 Sec  Memory Limit: 64 MBSubmit: 1006  Solved: ...