Package global.sandbox.xmlutilities

Utilities and Tools that makes XML parsing and validation more easier.

See:
          Description

Class Summary
NamespaceContextImpl Simple implementation of the NamespaceContext.
XMLTools Static version of the XMLUtilities class.
XMLUtilities This class provides simple XML utilities.
 

Package global.sandbox.xmlutilities Description

Utilities and Tools that makes XML parsing and validation more easier. There are two ways to use this package:

Static methods are good for simple usages. It shares one internal instance of XMLUtilities. Standalone XMLUtilities instance is good for multi-threading environment, is a little bit faster and finally—simplifies usage because of each method—in contrast to appropriate static method in XMLTools—throws less exceptions.

Functions, Methods and Tools

Category Method Availablity
in XMLUtilities in XMLTools
XML Loading from File to Document X X
from Stream to Document X X
from String to Document X
from String to Source X
Conversions Document to Source X
Document to String X X
Source to String X X
Validation XML validation against XMLSchema X X
XPath evaluation evaluate XPath that results to NodeList X X
evaluate XPath that results to single Node X X
Transformation from Sources to Document X X
from Templates and Source to Document X X
from Sources to String X X
from Templates and Source to String X X
Legend
Not available
X Available

XML Loading

The routines are defined in XMLTools and partially in XMLUtilities. The names of the methods starts with loadDocument or loadSource.
The following example loads XML content from specified resource. The static method returns Document and throws two Exceptions:
NoSuchResourceException
if the resource does not exist
XMLLoadingException
this exception coveres all "technical" exceptions
package global.sandbox.xmlutilities.demo;

import global.sandbox.xmlutilities.XMLTools;
import java.io.IOException;
import java.io.InputStream;
import org.w3c.dom.Document;

public class XMLLoading {

    public static Document loadXMLFromResourceAsDocument(Class clazz, String name)
            throws NoSuchResourceException, XMLLoadingException {
        InputStream is = clazz.getResourceAsStream(name);

        if (is == null) {
            throw new NoSuchResourceException(name);
        }

        try {
            return XMLTools.loadDocumentFromStream(is);
        } catch (Exception ex) {
            throw new XMLLoadingException(ex);
        } finally {
            try {
                is.close();
            } catch (IOException ex) {
                throw new XMLLoadingException(ex);
            }
        }
    }

    public static class NoSuchResourceException extends Exception {

        private static final long serialVersionUID = 1L;

        public NoSuchResourceException(String resourceName) {
            super(resourceName);
        }

    }

    public static class XMLLoadingException extends Exception {

        private static final long serialVersionUID = 1L;

        public XMLLoadingException(Throwable cause) {
            super(cause);
        }

    }

}
 

Conversions

XMLTools allows you to convert Document to Source or String.
The following method is part of the XMLLoading class from the example
above:
    public static Source loadXMLFromResourceAsSource(Class clazz, String name)
            throws NoSuchResourceException, XMLLoadingException {
        return XMLTools.documentToDOMSource(
                loadXMLFromResourceAsDocument(clazz, name));
    }
 

Validation

Both, XMLUtilities and XMLTools allows you to validate specified XML file against specified Schema. The following class shows you, how tu use the static variant:
package global.sandbox.xmlutilities.demo;

import global.sandbox.xmlutilities.XMLTools;
import javax.xml.transform.Source;
import org.w3c.dom.Document;

public class SchemaValidator {

    public static void validateXML(Source doc, Source schema)
            throws SchemaValidatorException, ValidationException {
        String result;

        try {
            result = XMLTools.validateXmlUsingSchema(doc, schema);
        } catch (Exception ex) {
            throw new SchemaValidatorException(ex);
        }

        if (result != null) {
            throw new ValidationException(result);
        }
    }

    public static void validateXML(Document doc, Document schema)
            throws SchemaValidatorException, ValidationException {
        validateXML(
                XMLTools.documentToDOMSource(doc),
                XMLTools.documentToDOMSource(schema));
    }

    public static class SchemaValidatorException extends Exception {

        private static final long serialVersionUID = 1L;

        public SchemaValidatorException(Throwable cause) {
            super(cause);
        }

    }

    public static class ValidationException extends Exception {

        private static final long serialVersionUID = 1L;

        public ValidationException(String message) {
            super(message);
        }

    }

}
 

XPath Evaluation

The following code shows how to easily evaluate XPath query. The method loadAttribute evaluates specified query (the query should end with @xxx) and tries to convert obtained Node to Attr. We can also try to cast Node to Attr and catch the ClassCastException.
package global.sandbox.xmlutilities.demo;

import global.sandbox.xmlutilities.NamespaceContextImpl;
import global.sandbox.xmlutilities.XMLTools;
import javax.xml.namespace.NamespaceContext;
import org.w3c.dom.Attr;
import org.w3c.dom.Element;
import org.w3c.dom.Node;

public class XPathEvaluation {

    final static NamespaceContext namespaces;

    static {
        final NamespaceContextImpl nspaces = new NamespaceContextImpl();
        nspaces.addNamespace(
                "ns",
                "http://hadrabap.googlepages.com/projects/xmlutilities/demo");

        namespaces = nspaces;
    }

    public static Attr loadAttribute(Element rootNode, String xPathQuery)
            throws XPathEvaluationException {
        Node node;
        try {
            node = XMLTools.getFirstNodeForXPath(
                    xPathQuery,
                    rootNode,
                    namespaces);
        } catch (Exception ex) {
            throw new XPathEvaluationException(ex);
        }

        if (node == null) {
            return null;
        }

        if (node.getNodeType() == Node.ATTRIBUTE_NODE) {
            return (Attr) node;
        } else {
            throw new XPathEvaluationException(
                    "Resulting node is not Attr, gotten "
                    + node.getNodeType());
        }
    }

    public static class XPathEvaluationException extends Exception {

        private static final long serialVersionUID = 1L;

        public XPathEvaluationException(String message) {
            super(message);
        }

        public XPathEvaluationException(Throwable cause) {
            super(cause);
        }

    }

}
 

Transformations

XMLUtilities and XMLTools also simplify transformations. They support Source-based and precompiled templates.
The following code demonstrates how to use the transformation support in XMLTools:
package global.sandbox.xmlutilities.demo;

import global.sandbox.xmlutilities.XMLTools;
import org.w3c.dom.Document;

public class Transformations {

    public static Document transform(Document doc, Document xsl)
            throws TransformationsException {
        try {
            return XMLTools.transformToDocument(
                    XMLTools.documentToDOMSource(xsl),
                    XMLTools.documentToDOMSource(doc));
        } catch (Exception ex) {
            throw new TransformationsException(ex);
        }
    }

    public static class TransformationsException extends Exception {

        private static final long serialVersionUID = 1L;

        public TransformationsException(Throwable cause) {
            super(cause);
        }

    }

}
 

For more details please check the test cases.

ChangeLog

Version Changes
1.0
  • Initial release
1.1
  • Added support for Namespaces
  • First public-domain release

TODO

Casted versions of getFirstNodeForXPath
current version provides only Node. It can try to cast to specialized Class such as Element or Attr. My approach is something like getFirstNodeForXPathAsAttr or getFirstNodeForXPathAsElement.
more conversion tools
currently, Document to Source is not available