简体   繁体   中英

Reading regular expression from XML using XPATH in Java

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.

my xml file "ErrorPatterns.xml" looks like this:

<?xml version="1.0" encoding="windows-1252" ?>
<errors>
  <pattern id="1">
    <reg> ERROR:</reg> 
  </pattern>
  <pattern id="2">
    <reg> dog </reg>
  </pattern>

</errors>

and my java code looks like this:

    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 < 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");    
         }
     }

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"

NodeList nodeList =              (NodeList)xpath.compile(expression).evaluate(doc,XPathConstants.NODESET);
            for (int i = 0; i < nodeList.getLength(); i++) { 
                 Pattern pattern2 = Pattern.compile("dog");
                 Matcher m2 = pattern2.matcher(ab);
                 if(m2.find())
                 {
                     System.out.println("Yaay");    
                 }
             }

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.

Thanks

Your problem is the extra whitespace in your XML. In particular, the regexes contained in your file are " ERROR:" and " dog " (note the whitespace), not "ERROR:" and "dog" as you may have been expecting.

For this reason, the dog regex (which matches a space, followed by "dog", followed by a space) doesn't match your test string because it doesn't contain a space before the word "dog".

Either remove the extra whitespace from your XML file, or change your test string to the following (for example):

String ab = " dog is barking"; // Note the extra space at the front

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM