lazyprogrammer
lazyprogrammer

Reputation: 629

Parsing CSS like file with Java

I am working on something that involves a file structure similar to that of CSS but its a bit different
from CSS. Here is the structure of the file

 <ELEMENT NAME>{
 Element attributes..1
 Element attributes..2
 Element attributes..3
 }

I have written a method to get Element Name

  public String getElementName(File jSfile){
    String elementName=null;
    StringBuffer sb = null;
    try{
    BufferedReader br=new BufferedReader(new FileReader(jSfile));
    String line=null;
    while((line=br.readLine())!=null){
    Pattern element=Pattern.compile("\\<(.+?)\\>",Pattern.DOTALL);
    Matcher match=element.matcher(line);
    match.find();
    return match.group(1);
    }
    }
    catch(Exception e){
    return e.getLocalizedMessage();
    }
    return elementName;

}

And use it like this..

 public static void main(String arg[]){
 CSSReader cs=new CSSReader();
 File f=new File("C:/Users/foo/bar/cascade.xyz");
 String z=cs.getElementName(f);
 System.out.print(z);
 }

But it always says 'No match found'

EDIT I found that the file contains more than 1 sequence of which had different name. When I removed all other's and kept only one the code worked.

Sorry for being noob here.....DOES ANY ONE KNOW HOW I WOULD GO ABOUT MULTILINE....thanks a ton Where am I going wrong

Upvotes: 0

Views: 144

Answers (2)

MildWolfie
MildWolfie

Reputation: 2532

You could declare your String line before the while loop, and change your check for the while loop to assign, and then check for null:

String line;
while ((line = br.readLine()) != null){
    // Do stuff with line
}

EDIT: Updated answer to reflect updated question

To account for multiple Elements, you could change your method to fill a list with each string that matches, rather than returning the first match. After the while loop completes, return that list.

Upvotes: 0

davidrac
davidrac

Reputation: 10738

You have 2 places where you write br.readLine(). The first is within the while condition and the second within the body. So the line that is read by the first one never gets used. I suspect this is the line that contains the token you are looking for.

Try changing this:

while(br.readLine()!=null){
    String line=br.readLine();

Into something like this:

String line = null;
while((line = br.readLine())!=null){

Upvotes: 3

Related Questions