Java HTML / XML How to - Use conditions in XPath expressions








Question

We would like to know how to use conditions in XPath expressions.

Answer

import java.util.HashMap;
import java.util.Map;
//from   w  w  w  . j a va2  s . co  m
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;

public class Main {
  private static Map<String, String> mappings = new HashMap<String, String>();
  static {
    mappings.put("package", "Package");
    mappings.put("libapp", "Application");
    mappings.put("module", "Module");
  }

  public static void main(String[] args) throws Throwable {
    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();
    String entryType = null;
    XPathExpression[] expressions = new XPathExpression[] {
        xpath.compile("local-name(*[local-name() = 'package'])"),
        xpath.compile("local-name(*[local-name() = 'libapp'])"),
        xpath.compile("local-name(*[local-name() = 'module'])") };

    DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance();
    DocumentBuilder parser = fac.newDocumentBuilder();
    Document doc = parser.parse(args[0]);

    for (int i = 0; i < expressions.length; i++) {
      String found = (String) expressions[i].evaluate(doc.getDocumentElement(),
          XPathConstants.STRING);
      entryType = mappings.get(found);
      if (entryType != null && !entryType.trim().isEmpty()) {
        break;
      }
    }
    System.out.println(entryType);
  }
}