Use dom4j to create and modify XML

Source: Internet
Author: User
Tags processing instruction ibm developerworks

Dom4j is an open-source XML framework for parsing XML documents. This document describes how to use the parser included in dom4j to create and modify an XML document.
The dom4j API contains a tool for parsing XML documents. This document uses the parser to create an example XML document. Listing 1 shows the example XML Document Catalog. xml.
Listing 1. Example XML document (catalog. XML)
<? XML version = "1.0" encoding = "UTF-8"?>
<Catalog>
<! -- An XML catalog -->
<? Target instruction?>
<Journal title = "XML zone" publisher = "IBM developerworks">
<Article level = "intermediate" date = "December-1, 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.

Listing 2. 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 = "Introductory" date = "October-2002">
<Title> create flexible and extensible XML schemas </title>
<Author>
<Firstname> Ayesha </firstname>
<Lastname> Malik </lastname>
</Author>
</Article>
</Journal>
</CATALOG>
Compared with W3C Dom APIs, the advantage of using the parser included in dom4j is that dom4j has local XPath support. The Dom parser does not support selecting nodes using XPath. This article includes the following parts:

Preset
Create document
Modify document
Preset
This parser can be obtained from the http://dom4j.org. By setting the dom4j-1.4/dom4j-full.jar to be accessible in classpath, the file includes the dom4j class, the XPath engine, and the sax and Dom interfaces. If you have used the sax and Dom interfaces included in the jaxp parser, add the dom4j-1.4/dom4j. jar to classpath. Dom4j. Jar includes the dom4j class and XPath engine, but does not contain the interfaces of Sax and Dom.
Back to Top
Create document
This section describes how to use the dom4j API to create an XML document and create the example XML Document Catalog. xml.
Use the Import Statement to import the dom4j API class:
Import org. dom4j. Document;
Import org. dom4j. documenthelper;
Import org. dom4j. element;
Use the deleenthelper class to create a document instance. Documenthelper is the dom4j API factory class that generates XML document nodes.
Document document = incluenthelper. createdocument ();

Use the addelement () method to create the root element catalog. Addelement () is used to add elements to an XML document.
Element catalogelement = Document. addelement ("catalog ");
Add the comment "an XML catalog" using addcomment () in the catalog element ".
Catalogelement. addcomment ("an XML catalog ");
Add a processing instruction in the catalog element using the addprocessinginstruction () method. Catalogelement. addprocessinginstruction ("target", "text ");
Use the addelement () method in the catalog element to add the journal element.
Element journalelement = catalogelement. addelement ("journal ");
Use the addattriher () method to add the title and publisher attributes to the journal element.
Journalelement. addattribute ("title", "XML zone ");
Journalelement. addattriher ("publisher", "IBM developerworks ");
Add a journal element to the article element.
Element articleelement = journalelement. addelement ("article ");
Adds the level and date attributes to the article element.
Articleelement. addattribute ("level", "intermediate ");
Articleelement. addattribute ("date", "December-2001 ");
Add the title element to the article element.
Element titleelement = articleelement. addelement ("title ");
Use settext () to set the text of the article element.
Titleelement. settext ("Java configuration with XML schema ");
Add the author element to the article element. Element authorelement = articleelement. addelement ("author ");
Add the firstname element to the author element and set the text of the element. Element firstnameelement = authorelement. addelement ("firstname ");
Firstnameelement. settext ("Marcello ");
Add the lastname element to the author element and set the text of the element.
Element lastnameelement = authorelement. addelement ("lastname ");
Lastnameelement. settext ("vitaletti ");
You can use adddoctype () to add document type descriptions.
Document. adddoctype ("catalog", null, "file: // C:/dtds/CATALOG. DTD ");
In this way, the document type description is added to the XML document:
<! Doctype catalog system "file: // C:/dtds/CATALOG. DTD">
To use document type definition (DTD) for document verification, doctype is required.
XML declaration <? XML version = "1.0" encoding = "UTF-8"?> Automatically added to the XML document.
The example program xmldom4j. Java in listing 3 is used to create the XML Document Catalog. xml.
Listing 3. Program for generating the XML Document Catalog. XML (xmldom4j. Java)
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 = incluenthelper. 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. addattriher ("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 (new file ("C:/CATALOG. xml"); output. Write (document); output. Close ();
}
Catch (ioexception e) {system. Out. println (E. getmessage () ;}} public static void main (string [] argv ){
Xmldom4j dom4j = new xmldom4j ();
Dom4j. generatedocument ();
}}
This section describes how to create an XML document. The next section describes how to use the dom4j API to modify the XML document created here.
Modify document
This section describes how to use the dom4j API to modify the example XML Document Catalog. xml.
Use saxreader to parse the XML Document Catalog. xml:
Saxreader = new saxreader ();
Document document = saxreader. Read (inputxml); saxreader is included in the org. dom4j. Io package.
Inputxml is a Java. Io. File Created from C:/CATALOG. xml. Use an XPATH expression to obtain a list of level nodes from the article element. If the level attribute value is "intermediate", change it 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 ");
}
Obtains 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 = 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 ");
}}
Modify the author element through a process similar to the title element. The example program dom4jparser. Java in Listing 4 is used to modify the catalog. XML document to a catalog-modified.xml document. Listing 4. program used to modify catalog. XML (dom4jparser. Java)
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. extends entexception;
Import org. dom4j. Io. saxreader;
Public class dom4jparser {public void modifydocument (File inputxml ){
Try {
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 ("maid-2002 ");
}
List = Document. selectnodes ("// article ");
Iter = List. iterator ();
While (ITER. hasnext ()){
Element element = (element) ITER. Next (); 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 = 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) ITER. next (); 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 (new file ("C:/CATALOG/catalog-modified.xml"); output. Write (document );
Output. Close ();
}
Catch (incluentexception 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 file ("C:/CATALOG. xml "));
}
} This section describes how to use the parser in dom4j to modify the sample XML document. This parser does not use DTD or mode to verify the XML document. If the XML document requires verification, you can use dom4j and jaxp sax Parser.

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.