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
  • del.icio.us
  • StumbleUpon
  • Digg
  • TwitThis
  • Mixx
  • Technorati
  • Facebook
  • NewsVine
  • Reddit
  • Google
  • LinkedIn
  • YahooMyWeb

Related Posts of dom4j xml file reading and writing

  • The EJB3 Persistence

    EJB3 persistence with Hibernate is very similar to the mechanism: Environment: Server: JBOSS5.0 Database: MySQL5.0 1. Set up a data source First of all, in jboss-5.0.0.GA \ server \ default \ deploy, the establishment of a database used to connect the dat

  • hibernate generic generic DAO

    package org.lzpeng.dao; import java.io.Serializable; import java.util.List; import org.hibernate.Criteria; import org.hibernate.Query; import org.hibernate.criterion.Criterion; import org.springside.modules.orm.hibernate.Page; /** * * @version 2009-1-10 *

  • Servlet brief introduction

    Servlet brief introduction: Servlet is a small application server Are used to complete the B / S architecture, the client requests the response to treatment Platform independence, performance, able to run thread Servlet API for Servlet provides the s ...

  • First Hibernate Example

    Curd a simple example. Source does not contain the dependent libraries, or playing too much of the package. PO object Note: One must have the default constructor 2 non-final modified. Otherwise useless lazy loading. UserDAOImpl category code, and other co

  • Spring2.0 + hibernate3.1 + log4j + mysql demo

    applicationContext.xml Non-attachment jar package, necessary friends can send an email to todd.liangt @ gmail.com

  • Struts2 + hibernate + spring problem user log in

    dao layer services layer action jsp <tr> <td align="center"> <b> user name: </ b> </ td> <td> <s: textfield name = "czyNumber" cssClass = "textstyle" theme = "simple" size = &q

blog comments powered by Disqus
Recent
Recent Entries
Tag Cloud
Random Entries