DOM4J Java Programming __ Programming

Source: Internet
Author: User
Tags getmessage gettext processing instruction xpath ibm developerworks

DOM4J is an open source XML framework for parsing XML documents. This article describes how to use the parser contained in DOM4J to create and modify an XML document.

The dom4j API contains a tool to parse XML documents. This article will use this parser to create a sample XML document. Listing 1 shows this sample XML document, Catalog.xml.

<?xml version= "1.0" encoding= "UTF-8"?> <catalog> <!--an XML catalog--> <?target instruction?> & Lt;journal title= "XML Zone" publisher= "IBM developerWorks" > <article level= "Intermediate" date= "December-2001" > <title>java configuration with XML schema</title> <author> <firstname>marcello</ firstname> <lastname>Vitaletti</lastname> </author> </article> </journal> </ Catalog>

Then use the same parser to modify Catalog.xml, listing 2 is the modified XML document, Catalog-modified.xml.

 <?xml version= "1.0" encoding= "UTF-8"?> <catalog> <!--an XML catalog--> <?target instruction?> <journal title= "XML Zone" publisher= "IBM developerWorks" > <article "level=" date = "October-2002" > <title>create flexible and extensible XML schemas</title> <author> <firstname >Ayesha</firstname> <lastname>Malik</lastname> </author> </article> </journal > </catalog>

The benefit of using the parser included with DOM4J is that DOM4J has local XPath support, as compared to the consortium DOM API. The DOM parser does not support using XPath to select nodes.

This article includes the following sections:

• Pre-Setup
• Create document
• Modifying documents

Pre-Setup

This parser can be obtained from the http://dom4j.org. The settings enable Dom4j-1.4/dom4j-full.jar to be accessed in Classpath, which includes the Dom4j class, the XPath engine, and the SAX and DOM interfaces. If you have used the SAX and DOM interfaces contained in the JAXP parser, add Dom4j-1.4/dom4j.jar to the classpath. Dom4j.jar includes the Dom4j class and XPath engine, but does not contain SAX and DOM interfaces.

Create a document

This section discusses the process of creating an XML document using the DOM4J API and creates a sample XML document Catalog.xml.

Import the dom4j API class using the import statement:

Import java.io.*; Import java.util.regex.*; Import org.dom4j.Document; Import Org.dom4j.DocumentHelper; Import org.dom4j.Element; Import Org.dom4j.io.OutputFormat; Import Org.dom4j.io.XMLWriter; Import Org.apache.poi.xssf.usermodel.XSSFRow; Import Org.apache.poi.xssf.usermodel.XSSFSheet; Import Org.apache.poi.xssf.usermodel.XSSFWorkbook;

Create a document instance using the Documenthelper class. Documenthelper is the dom4j API factory class that generates XML document nodes. Java Code Document document = Documenthelper.createdocument ();




Use the AddElement () method to create the root element catalog. AddElement () is used to add elements to an XML document. Java code Element catalogelement = document.addelement ("catalog");




Add the annotation "an XML catalog" using the AddComment () method in the Catalog element. Java Code catalogelement.addcomment ("an XML catalog");




Add a processing instruction using the Addprocessinginstruction () method in the Catalog element. Java code catalogelement.addprocessinginstruction ("Target", "text");




Add the journal element using the AddElement () method in the Catalog element. Java code Element journalelement = Catalogelement.addelement ("journal");




Use the AddAttribute () method to add title and Publisher properties to the journal element.            Java code journalelement.addattribute ("title", "XML Zone"); Journalelement.addattribute ("publisher", "IBM developerWorks");




Adds a journal element to the article element. Java Code Element articleelement=journalelement.addelement ("article");




Increase the level and date attributes for the article element.         Java code Articleelement.addattribute ("level", "intermediate"); Articleelement.addattribute ("date", "December-2001");




Adds the title element to the article element. Java Code Element titleelement=articleelement.addelement ("title");




Use the SetText () method to set the text of the article element. Java code titleelement.settext ("Java Configuration with XML Schema");




Adds the author element to the article element. Java Code Element authorelement=articleelement.addelement ("author");




Adds the FirstName element to the author element and sets the text of the element.        Java Code Element firstnameelement=authorelement.addelement ("FirstName"); Firstnameelement.settext ("Marcello");




Adds the LastName element to the author element and sets the text of the element.        Java Code Element lastnameelement=authorelement.addelement ("LastName"); Lastnameelement.settext ("Vitaletti");




You can use the Adddoctype () method to add document type descriptions. Java Code document.adddoctype ("catalog", NULL, "FILE://C:/DTDS/CATALOG.DTD");




This adds the document type description to the XML document: Java code <! DOCTYPE Catalog SYSTEM "FILE://C:/DTDS/CATALOG.DTD" >


If a document is to be validated with a document type definition (DTD) document, there must be Doctype.

The XML declaration <?xml version= "1.0" encoding= "UTF-8"?> is automatically added to the XML document.

The example program shown in Xmldom4j.java is used to create an XML document Catalog.xml

Import org.dom4j.Document; Import Org.dom4j.DocumentHelper; Import org.dom4j.Element; Import Org.dom4j.io.XMLWriter; Import java.io.*; public class xmldom4j{public void Generatedocument () {Document document = Documenthelper.createdocument (); Element catalogelement = document.addelement ("catalog"); Catalogelement.addcomment ("an XML Catalog"); Catalogelement.addprocessinginstruction ("Target", "text"); Element journalelement = catalogelement.addelement ("journal"); Journalelement.addattribute ("title", "XML Zone"); Journalelement.addattribute ("publisher", "IBM developerWorks"); Element articleelement=journalelement.addelement ("article"); Articleelement.addattribute ("level", "intermediate"); Articleelement.addattribute ("date", "December-2001"); Element titleelement=articleelement.addelement ("title"); Titleelement.settext ("Java configuration with XML Schema"); Element authorelement=articleelement.addelement ("author"); Element firstnameelement=authorelement.addelement ("FirstName"); FirstnameelEment.settext ("Marcello"); Element lastnameelement=authorelement.addelement ("LastName"); Lastnameelement.settext ("Vitaletti"); Document.adddoctype ("Catalog", NULL, "FILE://C:/DTDS/CATALOG.DTD"); try{XMLWriter output = new XMLWriter (New FileWriter ("C:/catalog/catalog.xml")); Output.write (document); OU Tput.close (); catch (IOException e) {System.out.println (E.getmessage ());}} public static void Main (string[] argv) {xmldom4j dom4j=new xmldom4j (); Dom4j.generatedocument ();}}  

Saxreader Saxreader = new Saxreader (); Document document = Saxreader.read (Inputxml);


The Saxreader is included in the Org.dom4j.io package.

Inputxml is the java.io.File created from C:/catalog/catalog.xml. Use an XPath expression to obtain a list of level nodes from the article element. If the Level property value is "intermediate", Change to "introductory".

List List = Document.selectnodes ("//article/@level"); Iterator Iter=list.iterator (); while (Iter.hasnext ()) {attribute attribute= (attribute) iter.next (); if (Attribute.getvalue (). Equals ("intermediate") ) Attribute.setvalue ("introductory"); }

Gets the list of article elements, obtains an iterator from the title element in the article element, and modifies the text of the title element.

List = Document.selectnodes ("//article"); Iter=list.iterator (); while (Iter.hasnext ()) {element element= (Element) Iter.next (); Iterator Iterator=element.elementiterator ("title"); while (Iterator.hasnext ()) {element titleelement= (Element) Iterator.next (), if (Titleelement.gettext (). Equals ("Java Configuration with XML Schema ") Titleelement.settext (" Create Flexible and extensible XML Schema "); }}

Modifies the author element by using a procedure similar to the TITLE element.

The sample program shown in Listing 4 Dom4jparser.java is used to modify the Catalog.xml document to Catalog-modified.xml document.

Import org.dom4j.Document; Import org.dom4j.Element; Import Org.dom4j.Attribute; Import java.util.List; Import Java.util.Iterator; Import Org.dom4j.io.XMLWriter; Import java.io.*; Import org.dom4j.DocumentException; Import Org.dom4j.io.SAXReader; public class dom4jparser{public void Modifydocument (File inputxml) {try{Saxreader saxreader = new Saxreader (); Document document = Saxreader.read (Inputxml); List List = Document.selectnodes ("//article/@level"); Iterator Iter=list.iterator (); while (Iter.hasnext ()) {attribute attribute= (attribute) iter.next (); if (Attribute.getvalue (). Equals ("intermediate") ) Attribute.setvalue ("introductory"); List = Document.selectnodes ("//article/@date"); Iter=list.iterator (); while (Iter.hasnext ()) {attribute attribute= (attribute) iter.next (); if (Attribute.getvalue (). Equals ("December-2001" )) Attribute.setvalue ("October-2002"); List = Document.selectnodes ("//article"); Iter=list.iterator (); while (Iter.hasnext ()) {element element= (Element) Iter.next (); IterAtor iterator=element.elementiterator ("title"); while (Iterator.hasnext ()) {element titleelement= (Element) Iterator.next (), if (Titleelement.gettext (). Equals ("Java Configuration with XML Schema ") Titleelement.settext (" Create Flexible and extensible XML Schema "); } list = Document.selectnodes ("//article/author"); Iter=list.iterator (); while (Iter.hasnext ()) {element element= (Element) Iter.next (); Iterator Iterator=element.elementiterator ("FirstName"); while (Iterator.hasnext ()) {element firstnameelement= (Element) Iterator.next (); if (Firstnameelement.gettext (). Equals ("Marcello")) Firstnameelement.settext ("Ayesha"); } list = Document.selectnodes ("//article/author"); Iter=list.iterator (); while (Iter.hasnext ()) {element element= (Element) Iter.next (); Iterator Iterator=element.elementiterator ("LastName"); while (Iterator.hasnext ()) {element lastnameelement= (Element) Iterator.next (); if (Lastnameelement.gettext (). Equals ( "Vitaletti") Lastnameelement.settext ("Malik"); } XMLWriter output = new XMLwriter (New FileWriter ("C:/catalog/catalog-modified.xml")); Output.write (document); Output.close (); catch (Documentexception e) {System.out.println (E.getmessage ());} catch (IOException e) {System.out.println ( E.getmessage ()); } public static void Main (string[] argv) {dom4jparser dom4jparser=new dom4jparser (); Dom4jparser.modifydocument (New Fil E ("C:/catalog/catalog.xml")); }} 

The

section explains how to use the parser in dom4j to modify the sample XML document. This parser does not use DTDs or schemas to validate XML documents. If the XML document needs to be validated, it can be explained with the dom4j and JAXP SAX parser. &NBSP

The parser contained in DOM4J is an unauthenticated tool for parsing XML documents that can be integrated with JAXP, crimson, or Xerces. This article explains how to use the parser to create and modify XML documents.

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.