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
paaaternhas the value you think it does? Have you tried printing it? For that matter, is theforloop entered at all - are you sure yournodeListisn't empty? BTW, I think you probably mean "important", not "impertinent" :)System.out.println( ">" + paaatern + "<" );