Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Apache License 

import java.util.Map;
import java.util.TreeMap;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

public class Main {
    /**
     * the expression cache.
     */
    private static final Map<String, XPathExpression> EXPRESSIONS = new TreeMap<String, XPathExpression>();

    /**
     * Counts the elements which results from the xpath expression.
     * 
     * @param document the xml document.
     * @param xpath the expression
     * @return Returns -1 if no element was found.
     */
    public static int count(Document document, String xpath) throws XPathExpressionException {
        return count(null, document, xpath);
    }

    /**
     * Counts the elements which results from the xpath expression.
     * 
     * @param document the xml document.
     * @param xpath the expression
     * @param message The assert message.
     * @return Returns -1 if no element was found.
     */
    public static int count(String message, Document document, String xpath) throws XPathExpressionException {
        XPathExpression expression = EXPRESSIONS.get(xpath);
        NodeList list = null;

        if (expression == null) {
            expression = XPathFactory.newInstance().newXPath().compile(xpath);
            EXPRESSIONS.put(xpath, expression);
        }

        if ((list = (NodeList) expression.evaluate(document.getDocumentElement(),
                XPathConstants.NODESET)) != null) {
            return list.getLength();
        }

        return -1;
    }
}