Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import org.w3c.dom.Node;

import org.xml.sax.InputSource;
import javax.xml.namespace.NamespaceContext;
import javax.xml.namespace.QName;
import javax.xml.xpath.*;

import java.util.*;

public class Main {
    public static Object evalXPath(String xpath, InputSource source, QName type) throws XPathExpressionException {
        return newXPath(xpath).evaluate(source, type);
    }

    public static Object evalXPath(String xpath, Node source, QName type) throws XPathExpressionException {
        return newXPath(xpath).evaluate(source, type);
    }

    public static XPathExpression newXPath(String xpath) throws XPathExpressionException {
        return newXPathFactory().newXPath().compile(xpath);
    }

    public static XPathExpression newXPath(String xpath, final Map<String, String> namespaces)
            throws XPathExpressionException {
        final XPath xp = newXPathFactory().newXPath();
        xp.setNamespaceContext(new NamespaceContext() {
            @Override
            public String getNamespaceURI(String prefix) {
                return namespaces != null ? namespaces.get(prefix) : null;
            }

            @Override
            public String getPrefix(String namespaceURI) {
                if (namespaces == null) {
                    return null;
                } else {
                    final Iterator i = getPrefixes(namespaceURI);
                    if (i.hasNext()) {
                        return (String) i.next();
                    } else {
                        return null;
                    }
                }
            }

            @Override
            public Iterator getPrefixes(String namespaceURI) {
                if (namespaces == null) {
                    return null;
                } else {
                    ArrayList<String> list = new ArrayList<String>();
                    for (Map.Entry<String, String> entry : namespaces.entrySet()) {
                        if (entry.getValue().equals(namespaceURI)) {
                            list.add(entry.getKey());
                        }
                    }
                    return list.iterator();
                }
            }
        });
        return xp.compile(xpath);
    }

    public static XPathFactory newXPathFactory() {
        return XPathFactory.newInstance();
    }
}