java Dom4j解析Xml文件,java 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")); //此处注意,输出的是rootElement,不是document,是不带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); //此处注意,输出的是document,是带xml头的 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; } }
官网文档地址:
https://dom4j.github.io/
Java Dom4j解析xml常见问题
Java Dom4j设置Xml encoding编码
Java Dom4j Element属性为Null时不显示
Java Dom4j Element标签非对称结束,Java Dom4j Element以“/”结束
https://fanshuyao.iteye.com/blog/2436491
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
蕃薯耀 2016年3月1日 10:54:34 星期二
http://fanshuyao.iteye.com/
相关推荐
5. **事件驱动解析(SAX)**:除了传统的DOM解析外,DOM4J还支持SAX解析器,这种解析方式适用于处理大型XML文件,因为它不需要一次性加载整个文档到内存。 6. **Namespace支持**:DOM4J提供了对XML命名空间的全面...
2. **基本用法**:在Java程序中,首先需要导入dom4j库,然后使用`DocumentBuilderFactory`创建`DocumentBuilder`,接着使用`DocumentBuilder`解析XML文件,得到`Document`对象。你可以通过`Document`对象获取XML的根...
Java DOM4J解析XML是一种常见的处理XML文档的技术,它提供了灵活且高效的API,使得...通过理解上述DOM4J解析XML的基本概念、操作和示例,开发者可以有效地在Java项目中处理XML数据,无论是读取、创建还是修改XML文件。
在“dom4j解析xml文件(增删改查)”这个主题中,我们将深入探讨如何使用DOM4J来实现XML文档的四种基本操作:增加元素、删除元素、更新元素内容以及查询元素。 首先,让我们了解DOM4J的基本用法。在解析XML文件时,...
- **配置文件解析**: 许多应用使用XML作为配置文件的格式,DOM4J可以方便地读取和更新这些配置信息。 - **Web服务**: 在SOAP等协议中,XML是常用的数据传输格式,DOM4J能够帮助构建和解析这些XML消息。 - **文档生成...
在本示例中,我们将深入探讨如何使用DOM4J解析XML文件,以`CacheInit.java`作为我们的核心代码示例,并参考`emailTemplateConfig.xml`作为实际操作的对象。 首先,让我们了解XML(eXtensible Markup Language)。...
而DOM4J是Java中一个强大的、灵活的处理XML的库,它提供了丰富的API,使得XML的解析、创建、遍历以及修改变得更为简便。本篇文章将深入探讨如何使用DOM4J来解析XML文件,以及通过示例代码来展示其基本操作。 首先,...
本篇文章将详细介绍如何使用DOM(Document Object Model)和DOM4j这两种流行的方法来解析XML文件。 首先,DOM是一种标准的W3C推荐的解析XML的方法,它将整个XML文档加载到内存中,形成一个树形结构,便于程序进行...
接下来,我们将创建一个`SAXReader`实例,它是DOM4J中的解析器,用于读取XML文件: ```java SAXReader reader = new SAXReader(); ``` 然后,使用`reader`读取XML文件并获取`Document`对象,`Document`代表整个XML...
1、xml文档解析 2、 dom4j解析xml 3、实现xml文件解析 xml字符串解析 xml MAP键值对解析 4、实现xml写入与生成文件
使用 dom4j 解析 XML dom4j 解析 XML dom4j解析xml
### 使用DOM4j解析XML文件:提升开发效率与代码可读性 在现代软件开发中,XML(Extensible Markup Language)是一种广泛使用的数据交换格式,它以人类可读的文本形式存储结构化信息。然而,如何高效、准确地解析XML...
总结,DOM4J为Java开发者提供了强大的XML处理能力,无论是解析、创建还是修改XML配置文件,都能轻松应对。通过学习和掌握DOM4J,你将能够更好地管理和维护基于XML配置的Java项目。请务必参考提供的文档和源码,以便...
为了在Java项目中使用DOM4J解析XML,你需要将这两个jar文件(dom4j-1.6.1和jaxen-1.1-beta-7.jar)添加到你的类路径(classpath)中。这可以通过在IDE中配置构建路径,或者在命令行中指定 `-cp` 参数来完成。一旦...
DOM4J是一个非常流行的、强大的Java XML API,它提供了灵活且高效的方式来解析、创建、修改XML文档。本文将深入探讨如何使用DOM4J进行XML解析,并通过实例来帮助理解。 首先,让我们了解DOM4J的基本概念。DOM4J是...
Java提供了多种解析XML的API,包括SAX(Simple API for XML)、DOM(Document Object Model)以及DOM4J。下面我们将详细探讨这些解析方式及其在实际开发中的应用。 1. SAX解析器: SAX是一种基于事件驱动的解析器,...
在这个项目中,我们利用DOM4J来解析XML文件,并通过Java的反射机制将解析出的信息存储到特定的类中。 首先,我们需要了解XML的基本概念。XML(Extensible Markup Language)是一种标记语言,常用于数据交换和结构化...
DOM4J不仅是一个解析XML的工具,还可以用作XML数据绑定库,将XML数据映射到Java对象。此外,DOM4J还支持Java 5的注解,这使得XML文档的处理更加直观和简洁。结合其灵活性和高性能,DOM4J成为Java开发人员处理XML文档...
Java DOM4J解析XML详解 XML(eXtensible Markup Language)是一种用于标记数据的语言,广泛应用于数据交换、配置文件和文档存储等领域。DOM4J是Java中一个强大的、轻量级的处理XML的库,它提供了丰富的API来读取、...