Xml (3) -- dom4j implements the crud operation, -- dom4jcrud

Source: Internet
Author: User
Tags xml parser

Xml (3) -- dom4j implements the crud operation, -- dom4jcrud

1. XML parsing technology Overview

(1) There are two XML parsing Methods: dom and sax.
Dom :( Document Object Model, that is, Document Object Model) is a standard XML processing method recommended by W3C organizations.
Sax: (Simple API for XML) is not an official standard, but it is a de facto standard of the XML community. Almost all XML Parser supports it.
(2) XML Parser (software/implementation class)
Crimson (SUN), Xerces (IBM-> APACHE), and Aelfred2 (DOM4J open-source organization)
(3) XML parsing technology API/Development Kit (in use, be sure to import the jar package dom4j-1.6.1.jar, and then right-click "Butid Path ")
Jaxp (SUN/dom/sax ),

Jdom,

Dom4j

The above three types should be said to gradually increase the ease of use, the simplest is more than dom4j.

2.

In DOM4j, there are three ways to obtain the Document object:
(1) read the XML file and get the document Object (resolution)

SAXReader reader = new SAXReader ();

Document document = reader. read (new File ("input. xml "));

(2) parse the XML text to obtain the document object.

String text = "<members> </members> ";

Document document = incluenthelper. parseText (text );

(3) Actively create a document Object (create)
Document document = incluenthelper. createDocument (); // create a root node

Element root = document. addElement ("members ");

3. Write documents into XML files

(1) the document is in full English and is written directly without encoding.

XMLWriter writer = new XMLWriter (new FileWriter ("output. xml"); document. add (rootElement );
Writer. write (document );

Writer. flush ();

Writer. close ();
(2) The document contains Chinese characters and sets the encoding format for writing.

OutputFormat format = OutputFormat. createCompactFormat (); // compact

OutputFormat of = OutputFormat. createPrettyPrint (); // wrap Mode

OutputStream OS = new FileOutputStream ("src/cn/itcast/xml/dom4j/car. xml ");
XMLWriter xmlWriter = new XMLWriter (OS, format );

Or: (the encoding method "UTF-8" must be set for the output of Chinese characters ")

XMLWriter writer = new XMLWriter (new OutputStreamWriter (new FileOutputStream (filePath), "UTF-8"), OutputFormat. createPrettyPrint ());


XmlWriter. write (document );
XmlWriter. close ();


4. (1) Meaning of CRUD: CreateReadUpdateDelete add, delete, query, modify

(2) There are two types of XML Parser: DOM and SAX.
A) DOM reads the entire XML file to the memory at a time to form an inverted tree structure.
B) SAX reads the entire XML file to the memory multiple times.
C) The Document object represents the image of the XML file in the memory.
(3) Common APIs are as follows:
SAXReader saxReader = new SAXReader (); SAXReader is the core class of dom4j
Document document = saxReader. read ("*. xml ")
Document. getRootElement ()
Element. getName ()
Element. elements (): gets all direct child elements under this Element.
Element. elementText (): navigate from one Element to another and retrieve the text of the Element.
Element. element ("sex"): navigate from one Element to another
Element. attributeValue ("id"): obtains the attribute corresponding to an Element.
Element. addElement ("sex"). setText ("male"): adds a new Element and sets the text value of the Element.
OutputFormat format = OutputFormat. createPrettyPrint (): Write an XML file by using a thumbnail.
XMLWriter xmlWriter = new XMLWriter (OS, format): constructs an XML writer.
XmlWriter. write (document): writes the document Object in memory to the hard disk.
FirstCarElement. remove (firstCarPriceElement): deletes a direct child element from the direct parent element.

// FirstCarPriceElement. getParent (). remove (firstCarPriceElement): deletes the direct child element from the direct parent element.


5. Code practice (implement crud operations on xml, but r is included in cud of xml, so r is not written separately)

Xml source file (student. xml ):


<? Xml version = "1.0" encoding = "UTF-8"?>
<Person>
<Student num = "2014072201">
<Name> Yi ye Binzhou </name>
<Age> 22 </age>
<Risk sion> Software Engineering </risk sion>
</Student>
<Student num = "2014072202">
<Name> effort </name>
<Age> 21 </age>
<Risk sion> Software Engineering </risk sion>
<Sex> female </sex>
</Student>
</Person>



Test code (Demo. java ):


Package cn. wwh. www. xml. dom4j;


Import java. io. File;
Import java. io. FileOutputStream;
Import java. io. OutputStream;
Import java. io. OutputStreamWriter;
Import java. util. List;


Import org. dom4j. Attribute;
Import org. dom4j. Document;
Import org. dom4j. Element;
Import org. dom4j. io. OutputFormat;
Import org. dom4j. io. SAXReader;
Import org. dom4j. io. XMLWriter;
Import org. junit. Test;


/**
* Class: parses xml files using xml dom4j and implements (CRUD operations)
* Note:
* 1. xpp3reader Resolution Method
XPP3Reader xpp3Reader = new XPP3Reader ();
Document document = xpp3Reader. read (new File (filePath ));
I don't know why ????
*
*
* @ Author
* @ Version 1.0
* @ Creation Time: 10:39:47 AM
*/
Public class Demo2 {
Private final static String filePath = "src/cn/wwh/www/xml/dom4j/student. xml ";
// Add xml attributes and elements
@ Test
Public void create () throws Exception {
// The SAXReader parsing method is used:
SAXReader saxReader = new SAXReader ();
Document document = saxReader. read (new File (filePath ));
Element root = document. getRootElement ();
// Obtain Student, the first element of a Person.
Element firstElement = (Element) root. elements (). get (0 );
// Add an attribute id for the first Student. The attribute value is "19920101"
FirstElement. addAttribute ("id", "19920101 ");
FirstElement. addElement ("sex"). setText ("male ");



// Output everything under the root node
List <Element> elements = root. elements ();
System. out. println ("root nodes:" + elements. size () + "element ");
For (Element e: elements ){
// Obtain the attributes of student
Attribute attribute = e. Attribute (0 );
System. out. println ("tag name:" + e. getName ());
System. out. println (e. getName () + "attribute value:" + attribute. getData () + "\ n" +
"Attribute. getName ():" + attribute. getName () + "\ n" +
"Attribute. getText ():" + attribute. getText ());
// Obtain all sub-tags
List <Element> child = e. elements ();
For (Element element: child ){
System. out. println (element. getName () + ":" +

Element. getText ());
}
}
// Write the data to the xml file.
OutputStream OS = new FileOutputStream (filePath );
OutputFormat of = OutputFormat. createPrettyPrint ();
OutputStreamWriter osw = new OutputStreamWriter (OS, "UTF-8 ");
XMLWriter xmlWrite = new XMLWriter (osw, );
XmlWrite. write (document );
XmlWrite. flush ();
XmlWrite. close ();
}
// Modify the xml file
@ Test
Public void update () throws Exception {
SAXReader saxReader = new SAXReader ();
Document document = saxReader. read (new File (filePath ));
Element root = document. getRootElement ();
System. out. println (root. getName ());
// Obtain the first Student
Element firstStudent = (Element) root. elements (). get (0 );
Element sex = firstStudent. element ("sex ");
// FirstStudent. element ("sex"). setText ("female ");
System. out. println (sex. getName ());
Sex. setText ("male ");

// Write data into the xml file
OutputStream OS = new FileOutputStream (filePath );
OutputStreamWriter osw = new OutputStreamWriter (OS, "UTF-8 ");
OutputFormat of = OutputFormat. createPrettyPrint ();

XMLWriter xmlWriter = new XMLWriter (osw, );
XmlWriter. write (document );
XmlWriter. flush ();
XmlWriter. close ();
}

// Delete xml
@ Test
Public void delete () throws Exception {
SAXReader reader = new SAXReader ();
Document document = reader. read (new File (filePath ));
Element element = document. getRootElement ();
Element firstStudent = (Element) element. elements (). get (0 );
// Obtain the property id of Student
Attribute attribute = firstStudent. Attribute ("id ");
System. out. println (attribute. getName ());
FirstStudent. remove (attribute );
// FirstStudent. remove ();
// Delete the sex element under the first Student:
Element sex = firstStudent. element ("sex ");
Sex. getParent (). remove (sex );
// Sex. remove (sex );

// Write data back to the file
XMLWriter writer = new XMLWriter (new OutputStreamWriter (new FileOutputStream (filePath), "UTF-8"), OutputFormat. createPrettyPrint ());
Writer. write (document );
Writer. flush ();
Writer. close ();
}
}


Code test (only show create ):









How does javaweb Save the XML generated in an action method (operated by dom4j) as saved to the desired location?

// This is a code I wrote to generate xml. If necessary, you can send the dom4j package and instance to you, or parse the xml
Package com. zuxia. dom4j;

Import java. io. File;
Import java. io. FileOutputStream;
Import java. util. Iterator;
Import java. util. List;
Import java. util. collections;

Import org. dom4j. Document;
Import org. dom4j. Element;
Import org. dom4j. io. OutputFormat;
Import org. dom4j. io. SAXReader;
Import org. dom4j. io. XMLWriter;

/**
*
* Use dom4j to parse xml
*
* 1. Create a parser
*
* 2. Create a Document Object Document
*
* 3. Get the root node
*
*/
Public class Dom4jParseXML {

Public static void main (String [] args ){

// 1. Create a parser
SAXReader saxreader = new SAXReader ();

Document doc = null;
Try {
// 2. Create a Document Object Document
Doc = saxreader. read (new File ("src/studentinfo. xml "));
} Catch (Exception e ){
System. out. println ("An error occurred while reading the xml file! ");
}

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

// 4. Obtain the element
Iterator <Element> iter = root. elementIterator ();

While (iter. hasNext ()){

Element student = iter. next ();

System. out. println ("student ID:" + student. attributeValue ("stuno") + "\ t name:" + student. elementText ("name "));
}

// Prompt the user to add new data
Pipeline SC = new pipeline (System. in );
System. out. println ("Enter your student ID :");
String stuno = SC. nextLine ();

System. out. println ("Enter name :");
String name = SC. nextLine ();

System. out. println ("Enter age :");
String age = SC. nextLine ();

// Add data to Document
... The remaining full text>

How to Use dom4j to operate XML

Import java. io. File;
Import java. io. FileWriter;
Import java. util. Iterator;
Import java. util. List;
Import org. dom4j. Attribute;
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;

/**
* @ Author Holen Chen
*/

Public class Dom4jDemo {

Public Dom4jDemo (){
}

/**
* Create an XML document. The document name is determined by the input parameters.
* @ Param filename the file name to be created
* @ Return returns the operation result. Table 0 fails and table 1 is successful.
*/

Public int createXMLFile (String filename ){
/** Operation result returned. Table 0 failed, Table 1 succeeded */
Int returnValue = 0;
/** Create a document object */
Document document = incluenthelper. createDocument ();
/** Create the root books of the XML document */
Element booksElement = document. addElement ("books ");
/** Add a line of comment */
BooksElement. addComment ("This is a test for dom4j, holen, 2004.9.11 ");
/** Add the first book node */
Element bookElement = booksElement. addElement ("book ");
/** Add the show parameter content */
BookElement. addAttribute ("show", "yes ");
/** Add a title node */
Element titleElement = bookElement. addElement ("title ");
/** Set content for title */
TitleElement. setText ("Dom4j Tutorials ");
/** Two books after similar completion */
BookElement = booksElement. addElement ("book ");
BookElement. addAttribute ...... remaining full text>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.