dom4j xml file reading and writing

This document contains four parts:

<! - [If! SupportLists] -> Ø <! - [Endif] -> write XML Example

<! - [If! SupportLists] -> Ø <! - [Endif] -> modify the XML

<! - [If! SupportLists] -> Ø <! - [Endif] -> Read XML Example

<! - [If! SupportLists] -> Ø <! - [Endif] -> Task Description: Using recursion to complete the reading of any xml file

Write file example:

/ **

Task Description: Using JAVA program output the following xml document: class.xml

<? Xml version = "1.0" encoding = "GBK"?>

<root year="2008">

<boss> take the lead in Big Brother </ boss>

<class teacher=" John "> group </ class>

<class teacher=" Dick "> second class </ class>

<class teacher=" Zhang sanfeng "> Three </ class>

</ Root>

* /

package chapter12.dom4j;

import java.io.FileWriter;

import org.dom4j.Document;

import org.dom4j.DocumentHelper;

import org.dom4j.Element;

import org.dom4j.io.OutputFormat;

import org.dom4j.io.XMLWriter;

public class WriteDemo {

public static void main (String [] args) throws Exception {

/ / Create a document object

Document doc = DocumentHelper. CreateDocument ();

/ / Create the root node <lovo> </ lovo>

Element root = doc.addElement ("root");

/ / Add attribute node <root year="2008"> </ root>

root.addAttribute ("year", "2008");

root.addElement ("boss"). addText ("take the lead in Big Brother");

/ / Add the text with attributes and child nodes <class teacher=" John "> group </ class>

root.addElement ("class"). addAttribute ("id", "01"). addAttribute ("teacher", "Joe Smith"). addText ("class");

root.addElement ("class"). addAttribute ("id", "02"). addAttribute ("teacher", "John Doe"). addText ("second class");

root.addElement ("class"). addAttribute ("id", "03"). addAttribute ("teacher", "Chi Master"). addText ("Three");

/ / Save (specify code)

FileWriter out1 = new FileWriter ("class.xml");

OutputFormat format = OutputFormat. CreatePrettyPrint (); / / createCompactFormat, createPrettyPrint

format.setEncoding ("GBK");

XMLWriter out2 = new XMLWriter (out1, format); / / specify the format

out2.write (doc);

out2.close ();

}

}

Modify the file example:

/ **

* Task Description: The following class.xml id = 02 nodes in the text changed to "project two", teacher to "take the lead in Big Brother"

<? Xml version = "1.0" encoding = "GBK"?>

<root year="2008">

<boss> take the lead in Big Brother </ boss>

<class teacher=" John "> group </ class>

<class teacher=" Dick "> second class </ class>

<class teacher=" Zhang sanfeng "> Three </ class>

</ Root>

* /

package chapter12.dom4j;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileWriter;

import java.io.InputStream;

import java.io.InputStreamReader;

import java.util.List;

import org.dom4j.Document;

import org.dom4j.DocumentException;

import org.dom4j.Element;

import org.dom4j.io.OutputFormat;

import org.dom4j.io.SAXReader;

import org.dom4j.io.XMLWriter;

public class ModifyDemo {

public static void main (String [] args) throws Exception {

StringBuffer sb = new StringBuffer ();

SAXReader reader = new SAXReader ();

/ / Get document object

Document doc = null;

try {

/ / Specify the encoding, to avoid

InputStream isr = new FileInputStream (new File ("class.xml"));

doc = reader.read (new InputStreamReader (isr, "GBK"));

isr.close ();

} Catch (DocumentException e) {

e.printStackTrace ();

}

/ / Get list of nodes using XPATH expressions

List <Element> list = doc.selectNodes ("/ / root / class");

/ / Create an iterator.

for (Element ele: list) {

String id = ele.valueOf ("@ id");

if (id! = null & & id.equals ("02")) {

ele.setText ("item two");

ele.setAttributeValue ("teacher", "take the lead in Big Brother");

}

}

/ / Save (specify code)

FileWriter out1 = new FileWriter ("class.xml");

OutputFormat format = OutputFormat. CreatePrettyPrint ();

format.setEncoding ("GBK");

XMLWriter out2 = new XMLWriter (out1, format); / / specify the format

out2.write (doc);

out2.close ();

}

}

Read file example:

/ **

* Read class.xml, reads as follows:

<? Xml version = "1.0" encoding = "GBK"?>

<root year="2008">

<boss> take the lead in Big Brother </ boss>

<class teacher=" John "> group </ class>

<class teacher=" Dick "> second class </ class>

<class teacher=" Zhang sanfeng "> Three </ class>

</ Root>

** Required output of the following:

Root: root

class = class id = 01 teacher = connotes year = 2008

class = second class id = 02 teacher = John Doe year = 2008

class = Three id = 03 teacher = Chi Master year = 2008

teacher = Joe Smith

teacher = John Doe

teacher = Chi Master

* /

package chapter12.dom4j;

import java.io.File;

import java.io.FileInputStream;

import java.io.InputStream;

import java.io.InputStreamReader;

import java.util.List;

import org.dom4j.Attribute;

import org.dom4j.Document;

import org.dom4j.DocumentException;

import org.dom4j.Element;

import org.dom4j.io.SAXReader;

public class ReadDemo {

public static void main (String [] args) throws Exception {

StringBuffer sb = new StringBuffer ();

SAXReader reader = new SAXReader ();

/ / Get document object

Document doc = null;

try {

/ / Specify the encoding, to avoid

InputStream isr = new FileInputStream (new File ("class.xml"));

doc = reader.read (new InputStreamReader (isr, "GBK"));

isr.close ();

} Catch (DocumentException e) {

e.printStackTrace ();

}

/ / Get the root node

Element eleRoot = doc.getRootElement ();

System. Out. Println ("root:" + eleRoot.getName ());

/ / Get the specified path (multiple) node

List <Element> listClass = doc.selectNodes ("/ / root / class");

for (int i = 0; i <listClass.size (); i + +) {

/ / Get the current node

Element ele = listClass.get (i);

/ / Get the name and the text of the current node

sb.append (ele.getName () + "=" + ele.getText ());

/ / Get property value

sb.append ("id =" + ele.valueOf ("@ id"));

sb.append ("teacher =" + ele.valueOf ("@ teacher"));

/ / Get the parent node (text, attributes, ... ...)

sb.append ("year" + "=" + ele.getParent (). valueOf ("@ year") + "\ r");

}

System. Out. Println (sb.toString ());

/ / Demo: Get the specified path (s) properties

List <Attribute> list = doc.selectNodes ("/ / root / class / @ teacher");

/ / For (int i = 0; i <list.size (); i + +) {

/ / Attribute att = list.get (i);

/ / System.out.println (att.getName ()+"="+ att.getValue ());

/ /}

/ / Use JDK1.5 for each loop in the code to complete the above functions (contrast study)

for (Attribute att: list) {

System. Out. Println (att.getName () + "=" + att.getValue ());

}

}

}

Recursive Reading Example:

/ **
* Task Description: Using recursion to complete the reading of any xml file
* /
package xml.dom4j;

import java.io.File;
import java.util.Iterator;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

public class ReadDiGui {

public static void main (String [] args) {
ReadDiGui dr = new ReadDiGui ();
dr.prinatAllNode ();
}

public void prinatAllNode () {
SAXReader reader = new SAXReader ();

/ / Get document object
Document doc = null;
try {
doc = reader.read (new File ("class.xml"));
} Catch (DocumentException e) {
e.printStackTrace ();
}

/ / Get the root node
Element root = doc.getRootElement ();

/ / Loop all nodes
printAllChildNode (root);
}

/ **
* Print all the child nodes
* /
public void printAllChildNode (Element element) {
/ / Loop all the attributes of the current node
Iterator j = element.attributeIterator ();
while (j.hasNext ()) {
Attribute attribute = (Attribute) j.next ();
System.out.println (""
+ Attribute.getName ()
+ "="
+ Attribute.getText ());
}

for (int i = 0, size = element.nodeCount (); i <size; i + +) {
Node node = element.node (i);
if (node instanceof Element) {
System.out.println (
node.getName ()
+ "="
+ Node.getText ());

printAllChildNode ((Element) node); / / calls itself - recursion
}
}
}
}
===========================

Original works, for permission to reproduce, reprint, please be sure to hyperlink to the article indicated the original source , author information and this statement. Otherwise held liable. http://lavasoft.blog.51cto.com/62575/347348
<! - The body begin ->

Dom4j format escape character problem

1, components have to say XML CDATA

All in the XML document, the text will be parsed by a parser.

Only the text within the CDATA part will be ignored.

Illegal XML characters must be replaced with the appropriate entities.

If the XML document using a similar "<" character, then there will be a parser error because the parser will think this is the beginning of a new element.

< < Less than the number
> > Greater than
& & And
' ' Single quote
" " Quotes

Entity must be the symbol "&" quotation mark ";" at the end.
Note: Only the "<" character and "&" characters for XML is strictly prohibited. The rest are legal, in order to reduce errors, use the entity is a good habit.

CDATA Parts
All content within the CDATA will be ignored by the parser.

If the text contains a lot of "<" character and "&" characters - as program code, it is best to put them all into the CDATA parts.

Part of a CDATA to "<! [CDATA [" marked the beginning to the end of "]]>" tag:

CDATA Note:
CDATA CDATA between components can not contain components (not nested). If the CDATA part contains the character "]]>" or "<! [CDATA [", will most likely wrong, oh.

Also note that there are no spaces between the string "]]>" or line breaks.

2, Dom4j format escape character problem

person.xml

<? Xml version = "1.0" encoding = "UTF-8"?>
<Person>
<Name> Joe Smith </ name>
<Addr> <! [CDATA [The three-way <Xin Yuan> 19F ]]></ addr>
</ Person>

The above XML format when being Dom4j automatically be escaped, escaped reads as follows:

<? Xml version = "1.0" encoding = "GBK"?>

<person>
<toname> <! [CDATA [The three-way <Xin Yuan> 19F ]]></ toname>
</ Person>

This is obviously not the desired result, because the CDATA does not require sub-righteousness. How to deal with the problem, see the following processing procedures:

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

import java.io.IOException;
import java.io.StringWriter;
import java.util.Date;

/ **
* Created by IntelliJ IDEA.
*
* @ Author leizhimin 2010-7-10 16:03:39
* /
public class Person {
private String name;
private String addr;

public Person (String name, String addr) {
this. name = name;
this. addr = addr;
}

public static void main (String [] args) {
Person p = new Person ("Joe Smith", "the Third Way <Xin Yuan> 19F");
p.showXml ();
}

public void showXml () {
String xml1, xml2, xml3;
Document doc = DocumentHelper.createDocument ();
doc.setXMLEncoding ("GBK");
Element root = doc.addElement ("person");
if (addr! = null)
addElement (root, "toname", "<! [CDATA [" + this. addr + "]]>");
else
addElement (root, "toname", this. addr);

xml1 = doc.asXML (); / / default escape
xml2 = formatXml (doc, "GBK", true); / / escape
xml3 = formatXml (doc, "GBK", false); / / do not escape
System.out.println (xml1);
System.out.println ("-------------------------");
System.out.println (xml2);
System.out.println ("-------------------------");
System.out.println (xml3);
}

/ **
Under the specified element * add a new child element
*
* @ Param e the parent element
* @ Param name name of child elements
* @ Param value the value of sub-elements
* @ Return a new child element added
* /
public static Element addElement (Element e, String name, Object value) {
Element x = e.addElement (name);
if (value == null | | "". equals (value.toString (). trim ())) {
x.setText ("");
} Else if (value instanceof Date) {
x.setText (DateToolkit.toISOFormat ((Date) value));
} Else {
x.setText (value.toString ());
}
return x;
}

/ **
* Formatting XML documents
*
* @ Param document xml document
* @ Param charset the encoding of the string
* @ Param istrans whether the transfer of attributes and elements values
* @ Return string formatted XML
* /
public static String formatXml (Document document, String charset, boolean istrans) {
OutputFormat format = OutputFormat.createPrettyPrint ();
format.setEncoding (charset);
StringWriter sw = new StringWriter ();
XMLWriter xw = new XMLWriter (sw, format);
xw.setEscapeText (istrans);
try {
xw.write (document);
xw.flush ();
xw.close ();
} Catch (IOException e) {
System.out.println ("XML document format an exception occurs, please check!");
e.printStackTrace ();
}
return sw.toString ();
}
}

Output:

<? Xml version = "1.0" encoding = "GBK"?>
<person> <toname> <! [CDATA [The three-way <Xin Yuan> 19F ]]></ toname> </ person>
-------------------------
<? Xml version = "1.0" encoding = "GBK"?>

<person>
<toname> <! [CDATA [The three-way <Xin Yuan> 19F ]]></ toname>
</ Person>

-------------------------
<? Xml version = "1.0" encoding = "GBK"?>

<person>
<toname> <! [CDATA [The three-way <Xin Yuan> 19F ]]></ toname>
</ Person>

Process finished with exit code 0

It can be seen, the last output is really wanted.

Therefore, to control the escape of the problem, must be re-formatted XML, format, when you need to set:

xw.setEscapeText (false);

This article comes from " lava "blog, be sure to keep this source http://lavasoft.blog.51cto.com/62575/347348

分类:Java 时间:2011-01-14 人气:134
分享到:
blog comments powered by Disqus

相关文章

  • [Reprinted] JAVA on reading and writing XML documents 2010-09-25

    There are many ways to read and write XML ~ ~ JAVA in a rich class of the XML file at ~ ~ such XMLReader .... JDOM ... DOM and so on ~ ~ Here is what I found from online information and examples of successful pilot ~ ~ Using the DOM ~ ~ ~ do not need

  • Java four ways to parse XML files 2010-03-29

    1. Introduction 1) DOM (JAXP Crimson parser) DOM is platform-and language-independent manner in the official W3C standard XML documents. DOM is a hierarchical organization of nodes or a collection of pieces of information. This hierarchical structure allo

  • JAVA several analytical methods for XML 2010-04-05

    XML description for a more comprehensive or IBM's column: http://www.ibm.com/developerworks/cn/xml/theme/x-java.html Basically covers all aspects of JAVA with XML 1. Introduction 1) DOM (JAXP Crimson parser) DOM is platform-and language-independe ...

  • Java by XML Schema validation XML 2010-03-29

    Java by XML Schema validation XML XML validation in the XML processing is very common, if there is no effective way to verify the legitimacy of XML, often lead to many problems. XML validation by XML Schema (XSD) or DTD file to verify the syntax spec ...

  • java operation xml w3c and xml store your picture files 2010-03-29

    This article is reproduced, provenance http://hi.baidu.com/kelsen/blog/item/d552f2bfebc26b0d19d81f31.html

  • Java to read and write XML Summary 2010-06-09

    1. DOM (Document Object Model) This method is mainly provided by the W3C, xml file it all into memory, then the composition of the various elements of a data tree for quick access to each node. Therefore, system performance is consumed, compared to the la

  • Java operations the value of xml file 2010-10-04

    package net.fiyu.edit; import java.io.File; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.d

  • 在java中使用dom解析xml的示例分析 2013-10-02

    本篇文章介绍了,在java中使用dom解析xml的示例分析。需要的朋友参考下 dom是个功能强大的解析工具,适用于小文档 为什么这么说呢?因为它会把整篇xml文档装载进内存中,形成一颗文档对象树 总之听起来怪吓人的,不过使用它来读取点小东西相对Sax而言还是挺方便的 至于它的增删操作等,我是不打算写了,在我看教程的时候我就差点被那代码给丑到吐了 也正因为如此,才有后来那些jdom和dom4j等工具的存在…… 不多说,直接上代码 Dom解析示例 import java.io.File; impor

  • 在java中使用dom4j解析xml(示例代码) 2015-04-15

    鉴于目前的趋势,我们这里来讲讲Dom4j的基本用法,不涉及递归等复杂操作。Dom4j的用法很多,官网上的示例有那么点儿晦涩,这里就不写了 虽然Java中已经有了Dom和Sax这两种标准解析方式 但其操作起来并不轻松,对于我这么一个初学者来说,其中部分代码是活生生的恶心 为此,伟大的第三方开发组开发出了Jdom和Dom4j等工具 鉴于目前的趋势,我们这里来讲讲Dom4j的基本用法,不涉及递归等复杂操作 Dom4j的用法很多,官网上的示例有那么点儿晦涩,这里就不写了 首先我们需要出创建一个xml文档

  • java中使用sax解析xml的解决方法 2015-04-28

    本篇文章介绍了,在java中使用sax解析xml的解决方法。需要的朋友参考下 在java中,原生解析xml文档的方式有两种,分别是:Dom解析和Sax解析 Dom解析功能强大,可增删改查,操作时会将xml文档以文档对象的方式读取到内存中,因此适用于小文档 Sax解析是从头到尾逐行逐个元素读取内容,修改较为不便,但适用于只读的大文档 本文主要讲解Sax解析,其余放在后面 Sax采用事件驱动的方式解析文档。简单点说,如同在电影院看电影一样,从头到尾看一遍就完了,不能回退(Dom可来来回回读取) 在看

iOS 开发

Android 开发

Python 开发

JAVA 开发

开发语言

PHP 开发

Ruby 开发

搜索

前端开发

数据库

开发工具

开放平台

Javascript 开发

.NET 开发

云计算

服务器

Copyright (C) codeweblog.com, All Rights Reserved.

CodeWeblog.com 版权所有 黔ICP备15002463号-1

processed in 0.551 (s). 12 q(s)