"Parsing packages with dom4j" makes DOM-style operations on XML--readxml

Source: Internet
Author: User
Tags compact flush gettext trim

It Programmer development Essentials-all kinds of resources download list, history of the most IT resources, personal collection summary. package edu.dom4j.dom;

Import Java.io.FileWriter;

Import java.io.IOException;

Import Java.util.Iterator;

Import java.util.List;

Import Org.dom4j.Attribute;

Import org.dom4j.Document;

Import org.dom4j.DocumentException;

Import org.dom4j.Element;

Import Org.dom4j.Node;

Import Org.dom4j.io.OutputFormat;

Import Org.dom4j.io.SAXReader;

Import Org.dom4j.io.XMLWriter;

Import Org.junit.Test;

/**

* 1. Read the text of the specified label

* 2. Read the properties of the specified label

* 3. Product.xml documents are pretty print (beautiful) and

* Compact format (compression) style printed to System.out and file

* Note: Because Chinese is not processed here, the Chinese printed to the console and XML file will be garbled,

* specific processing methods See : DOM4J tool When modifying XML files Chinese garbled solution

* 4. The XML structure of the Document object is output by the recursive method

**/

public class ReadXML {

Private String xmlfile = "Webroot/product2.xml";

Private Attribute Attribute;

private node node;


Public Document GetDocument () throws Documentexception {

Get DOM4J Parser

Saxreader reader = new Saxreader ();

Read the XML document: Note that it is under the Org.dom4j.Document package

Document document = Reader.read (xmlfile);

return document;

}

  /*

* Read the Second <product> tab in the <specifications> tables and chairs </specifications> text

* But this is also a label for text and cannot be read

   */

@Test

public void Readxmltext () throws documentexception{

Document document = GetDocument ();

Get the root node of the XML document

Element root = Document.getrootelement ();

Get the <product> child node collection under the root node, using the elements (name) method

List<element> products = root.elements ("Product");

Get to two <product> nodes

Element product2 = products.get (1);

Because there is only one specifications tag under Pruduct2, the element (name) method

Element specifications = Product2.element ("Specifications");

Gets the text of the specifications node

String text = Specifications.gettext ();

System.out.println ("<specifications>" +text+ "</specifications>");

Output Results:<specifications> table </specifications> Chairs

}

//Read the category and inventory property values of the first <product> tag

@Test

public void Readxmlattr () throws documentexception{

Document document = GetDocument ();

Element root = Document.getrootelement ();

Element Product1 = root.element ("Product");

Get the value of the specified attribute one: Get Attribute Object

Attribute categoryattr = Product1.attribute ("category");

System.out.print ("<product" +categoryattr.getname () + "= '" +categoryattr.getvalue () + "'");

Get the specified attribute mode two: Get attribute property value directly

String Categoryvalue = product1.attributevalue ("inventory");

System.out.println ("inventory=" "+categoryvalue+" > ");

}

//product.xml documents are printed in pretty print (pretty) and compact format (compressed) style to System.out and file, respectively

@Test

public void Formatxml2system () throws Documentexception, ioexception{

Document document = GetDocument ();

/*

* Crud operation code for in-memory document objects

* ......

*/

1. Update the Document object to Product2.xml or new XML

XMLWriter writer = new XMLWriter (New FileWriter ("Webroot/product3.xml"));

Writer.write (document);

//Can call Writer.close (), close at the same time, call the Writer.flush (), but Chinese words, will appear garbled

Writer.flush ();

2. Print the Domcument object to the System.out in pretty print mode

OutputFormat format = Outputformat.createprettyprint ();

writer = new XMLWriter (System.out,format);

Writer.write (document);

Writer.flush ();

3. Print the Document object in compact format to System.out

format = Outputformat.createcompactformat ();

writer = new XMLWriter (System.out,format);

Writer.write (document);

Writer.flush ();

}

//The XML structure of the Document object is output through a recursive method

@Test

public void Printxml2system () throws documentexception{

Element root = GetDocument (). Getrootelement ();

Printelement (root);

}

///Print parameter node information, loop parameter node child node, recursive call to the method, output element node structure

public void Printelement (element Element) {

System.out.print ("<" +element.getname ());

Iterate the properties on the output LABEL element

for (Iterator<attribute> i = Element.attributeiterator (); I.hasnext ();) {

attribute = I.next ();

System.out.print ("" +attribute.getname () + "=" "+attribute.getvalue () +" ' ");

}

System.out.print (">");

Child nodes of the loop element

for (int j = 0,size = Element.nodecount (); j < size; J + +) {

node = Element.node (j);

if (node instanceof Element) {

System.out.println ();

Printelement (Element) node);

}else {

/*

* Here the. Trim () method must be, because when dom4j parsing,

* The space between the end tag and the next start tag is also an object

*/

System.out.print (Node.gettext (). Trim ());

}

}

System.out.println ("<" +element.getname () + "/>");

}

}


product2.xml File:

<?

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.