Example 6-25: Command-line tool validates XML against XPath rulesets

import java.net.URL;
import oracle.xml.parser.v2.*;
import org.w3c.dom.*;

public class XPathValidator {
  public static void main(String[] args) throws Exception {
    if (args.length == 2) {
      XPathValidator xpv = new XPathValidator();
      xpv.validate(args[0],args[1]);
    }
    else errorExit("usage: XPathValidator xmlfile rulesfile");
  }
  // Validate an XML document against a set of XPath Validation Rules
  public void validate(String filename, String rulesfile) throws Exception {
    // Parse the file to be validated and the rules file
    XMLDocument source = XMLHelper.parse(URLUtils.newURL(filename));
    XMLDocument rules  = XMLHelper.parse(URLUtils.newURL(rulesfile));
    // Get the name of the Ruleset file with valueOf
    String ruleset = rules.valueOf("/ruleset/@name");
    if (ruleset.equals("")) errorExit("Not a valid ruleset file.");
    System.out.println("Validating "+filename+" against " +ruleset+" rules...");
    // Select all the <rule>'s in the ruleset to evaluate
    NodeList ruleList = rules.selectNodes("/ruleset/rule");
    int rulesFound    = ruleList.getLength();
    if (rulesFound < 1) errorExit("No rules found in "+rulesfile);
    else {
      int errorCount = 0;
      for (int z = 0; z < rulesFound; z++) {
        XMLNode curRule = (XMLNode)ruleList.item(z);
        String  curXPath = curRule.valueOf(".").trim();
        // If XPath Predicate test fails, print out rule name as an err message
        if ( !test(source,curXPath) ) {
          String curRuleName = curRule.valueOf("@name");
          System.out.println("("+(++errorCount)+") "+curRuleName);
        }
      }
      if (errorCount == 0) System.out.println("No validation errors.");
    }
  }
  // Test whether an XPath predicate is true with respect to a current node
  public boolean test(XMLNode n, String xpath) {
    NodeList matches = null;
    try { return n.selectSingleNode("./self::node()["+xpath+"]") != null; }
    catch (XSLException xex) { /* Ignore */ }
    return false;
  }
  private static void errorExit(String m){System.err.println(m);System.exit(1);}
}