title: Reading regular expression from XML using XPATH in Java
body: <p>I have a set of regular expressions which are stored in a XML file, and i have a string that has to be matched against these regular expressions. To read the regular expressions , i am using XPath. </p>
  
  <p>my xml file "ErrorPatterns.xml" looks like this:</p>
  
  <pre><code>&lt;?xml version="1.0" encoding="windows-1252" ?&gt;
  &lt;errors&gt;
    &lt;pattern id="1"&gt;
      &lt;reg&gt; ERROR:&lt;/reg&gt; 
    &lt;/pattern&gt;
    &lt;pattern id="2"&gt;
      &lt;reg&gt; dog &lt;/reg&gt;
    &lt;/pattern&gt;
  
  &lt;/errors&gt;
  </code></pre>
  
  <p>and my java code looks like this:</p>
  
  <pre><code>    String ab = "dog is barking";
      File xmlFile = new File("ErrorPatterns.xml");
      DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
      DocumentBuilder dBuilder;
      dBuilder = dbFactory.newDocumentBuilder();
      Document doc = dBuilder.parse(new FileInputStream("ErrorPatterns.xml"));
      XPath xpath = XPathFactory.newInstance().newXPath();
      String expression ="/errors/pattern/reg";
      NodeList nodeList =         (NodeList)xpath.compile(expression).evaluate(doc,XPathConstants.NODESET);
      for (int i = 0; i &lt; nodeList.getLength(); i++) {
           String paaatern=nodeList.item(i).getFirstChild().getNodeValue().toString(); 
           Pattern pattern2 = Pattern.compile(paaatern);
           Matcher m2 = pattern2.matcher(ab);
           if(m2.find())
           {
               System.out.println("Yaay");    
           }
       }
  </code></pre>
  
  <p>When the above code is run, it exits without printing "Yaay". But if instead of reading the expression from xml and if directly given in the Pattern like in the code below , it prints "Yaay"</p>
  
  <pre><code>NodeList nodeList =              (NodeList)xpath.compile(expression).evaluate(doc,XPathConstants.NODESET);
              for (int i = 0; i &lt; nodeList.getLength(); i++) { 
                   Pattern pattern2 = Pattern.compile("dog");
                   Matcher m2 = pattern2.matcher(ab);
                   if(m2.find())
                   {
                       System.out.println("Yaay");    
                   }
               }
  </code></pre>
  
  <p>But its impertinent that i read the regular expression from the ErrorPatterns.xml and use them in the project. please guide as to how to do it.</p>
  
  <p>Thanks</p>