The DOM4J util Package
DOM4J's util package provides many utility classes for comparing nodes, reporting parsing errors, creating a Singleton Document object, etc. This section highlights some of the most useful.
Comparing multiple XML documents is a very common feature in any service-oriented architecture (SOA) application. To do this, you need to write a lot of if statements to compare each element data. DOM4J addresses this need with the NodeComparator utility class, which compares two nodes (attributes, elements, documents, etc.) for equality.
Compare2Docs.java loads the test.xml and test1.xml documents, which contain the same XML documents with the same data, parses and loads them into DOM4J, and compares them using NodeComparator. In this case, since both XML documents are same, it prints the equality message:
NodeComparator comparator = new NodeComparator();
if ( comparator.compare( d1, d2 ) == 0 ) {
System.out.println("Both documents are same.");
}
else
{
System.out.println("Both documents are different.");
}
Should you modify the data in one of the XML documents, you will see the inequality message. Had DOM4J come a bit earlier, I would have saved myself many late nights spent writing the cumbersome code to compare two XML documents.
The DOM4J XMLErrorHandler utility class provides an XML representation of the errors that can occur during XML parsing. This is a very elegant way of reporting invalid XML documents. In order to retrieve the SAXParsing errors, you need to set the error handler to the SAXReader:
reader.setErrorHandler(errorHandler);
When an exception occurs, the errors can be retrieved using the follow command:
Element root = ((XMLErrorHandler)reader.getErrorHandler()).getErrors();
ErrorDemo.java contains code to demonstrate this DOM4J feature.
DOM4J's SimpleSingleton utility class provides common factory access for the same object instance. This implementation creates a new instance from the class specified (Document) and does not create a new one unless it is reset. This is a very useful feature for building a single Document object across different application modules.
DOM4J to the Rescue
XML technology is perfect for developing integrated applications. However, parsing and retrieving XML data in your Java application requires thousands of lines of simple but cumbersome code. Enter DOM4Jand not a moment too soon. You can look forward for numerous lightweight, high-performance enterprise Java applications when you use DOM4J.