Reprinted dom4j xml parsing

sponsored links
Parsing XML using dom4j
Use domj4 API to create and modify XML document level: primary
dom4j is an open source parsing XML documents XML framework. This article describes how to use the parser included in the dom4j to create and modify XML documents.
dom4j API XML document contains an analysis tool. This article will use the parser to create a sample XML document. Listing 1 shows the sample XML document, catalog.xml.

Listing 1. Sample 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-2001">
<title> Java configuration with XML Schema </ title>
<author>
<firstname> Marcello </ firstname>
<lastname> Vitaletti </ lastname>
</ Author>
</ Article>
</ Journal>
</ Catalog>

And then use the same parser modify catalog.xml, Listing 2 is the modified XML document, catalog-modified.xml.

Listing 2. 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="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 the W3C DOM API, use dom4j parser contained in the benefits of local ownership is dom4j XPath support. DOM parser does not support the use of XPath to select nodes.

This includes the following sections:

Modify the document to create a document preset preset

This parser can get from http://dom4j.org. By setting the classpath to dom4j-1.4/dom4j-full.jar able to access, the file includes dom4j class, XPath, and SAX and DOM interfaces engines. If you have used the JAXP SAX parser and DOM interfaces are included, adding to the classpath dom4j-1.4/dom4j.jar. dom4j.jar including the dom4j classes and XPath engine, but not including SAX and DOM interfaces.

Create a document

This section discusses the use of dom4j API to create XML documents in the process and create a sample XML document catalog.xml.

Use the import statement to import the dom4j API categories:

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

Create a document using DocumentHelper class instance. DocumentHelper is to generate XML document node of the dom4j API factory class.

Document document = DocumentHelper.createDocument ();

Use the addElement () method to create the root element catalog. addElement () is used to add elements to the XML document.

Element catalogElement = document.addElement ("catalog");

Elements in the catalog using addComment () method to add a comment "An XML catalog".

catalogElement.addComment ("An XML catalog");

Elements in the catalog using addProcessingInstruction () method to add a processing instruction.

catalogElement.addProcessingInstruction ("target", "text");

Elements in the catalog using addElement () method to increase journal element.

Element journalElement = catalogElement.addElement ("journal");

Use addAttribute () method to add elements to the journal title and publisher attributes.

journalElement.addAttribute ("title", "XML Zone");
journalElement.addAttribute ("publisher", "IBM developerWorks");

Add the journal element to the article element.

Element articleElement = journalElement.addElement ("article");

Increase the level for the article and the date property element.

articleElement.addAttribute ("level", "Intermediate");
articleElement.addAttribute ("date", "December-2001");

Add elements to the article title element.

Element titleElement = articleElement.addElement ("title");

Use setText () method to set the text of article elements.

titleElement.setText ("Java configuration with XML Schema");

Elements in the article to add author element.

Element authorElement = articleElement.addElement ("author");

Adding firstname element in the author element and set the element's text.

Element firstNameElement = authorElement.addElement ("firstname");
firstNameElement.setText ("Marcello");

Increase in the author element and set the lastname element text element.

Element lastNameElement = authorElement.addElement ("lastname");
lastNameElement.setText ("Vitaletti");

You can use addDocType () method to add a document type description.

document.addDocType ("catalog", null, "file: / / c: / Dtds / catalog.dtd");

This increase in the document to the XML document type description:

<! DOCTYPE catalog SYSTEM "file: / / c: / Dtds / catalog.dtd">

If the document you want to use the document type definition (DTD) document verification, you must have Doctype.

XML declaration <? Xml version = "1.0" encoding = "UTF-8"?> Automatically added to the XML document.

Listing 3 shows examples of procedures used to create XML documents XmlDom4J.java catalog.xml.

Listing 3. Catalog.xml procedures generate XML documents (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 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 (new File ("c: / catalog / 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 discusses the process of creating XML documents, the next section will use the dom4j API changes introduced to create the XML document here.

Back to top

Modify the document

This section describes how to use the dom4j API modify the sample XML document catalog.xml.

Parsing XML documents using SAXReader catalog.xml:

SAXReader saxReader = new SAXReader ();
Document document = saxReader.read (inputXml);

SAXReader included in org.dom4j.io package.

inputXml from c: / catalog / catalog.xml create a java.io.File. Use XPath expressions to get from the article level element node list. If the level attribute value is "Intermediate" will be changed 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");
)

Get a list of article elements, from the article's title element by element in an iterator, and modify the title element of the text.

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");
))

Elements through a similar process and modify the title author element.

Listing 4 shows an example program Dom4JParser.java catalog.xml document used to modify the document into the catalog-modified.xml.

Listing 4. Catalog.xml to modify the procedures (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.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 (new File ("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 File ("c: / catalog / catalog.xml"));
)
)

This section describes how to use the dom4j parser changes in the sample XML document. This parser does not use DTD or schema validation, XML. If you need to validate XML documents, can be explained using dom4j with the JAXP SAX parser.
  • del.icio.us
  • StumbleUpon
  • Digg
  • TwitThis
  • Mixx
  • Technorati
  • Facebook
  • NewsVine
  • Reddit
  • Google
  • LinkedIn
  • YahooMyWeb

Related Posts of Reprinted dom4j xml parsing

  • spring myfaces hibernate richfaces

    1.web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j

  • Spring + Hibernate to use Glassfish Database Connection Pool

    applicationContext.xml file content <? xml version = "1.0" encoding = "UTF-8"?> <beans xmlns = " http://www.springframework.org/schema/beans " xmlns: xsi = " http://www.w3.org/2001/XMLSchema-instance " ...

  • Process migration from tomcat to websphere changes

    Process migration from tomcat to websphere changes Because customers use the web application server software used by different what tomcat5, tomcat6, websphere5.1, websphere6.1, weblogic8, and so on, and the software used inconsistent standards, ibm's

  • JAVA EE JSP_JNDI

    dsfdsa http://lindows.javaeye.com/admin/blogs/213348 Tomcat 6 with the connection pool data source configuration http://www.blogjava.net/ec2008/archive/2008/07/19/216063.html project: test Driver path: D: \ workspace \ test \ WebRoot \ WEB-INF \ lib ...

  • Hibernate.cfg.xml configuration file (including the primary key generation strategy Introduction)

    Hibernate.cfg.xml configuration file: <? xml version = "1.0" encoding = "utf-8"?> <! DOCTYPE hibernate-configuration PUBLIC "- / / Hibernate / Hibernate Configuration DTD / / EN" "hibernate-configuration-2.0.dtd

  • 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

  • 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 ...

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

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

  • Based on JDBC, JPA Annotation achieve simple CRUD Generic Dao

    The origin of ideas are pretty long history of reasons: [Use iBATIS history] The use of iBATIS has been a long time, the system is to use the CRUD template tool to generate the code, although there are tools to generate, but looked at a lot of CRUD the Sq

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