I noticed that the parse() method of ParserDelegator creates a DocumentParser object to do the actual parsing of the HTML document. DocumentParser contains a method getCurrentLine(). So, I tried to extending ParserDelegator so I could access Document Parser. However, the getCurrentLine method is protected so I ended up also extending DocumentParser.
You probably have code something like:
new MyParserDelegator().parse(reader, this, false);
This should be replaced with:
parser = new MyParserDelegator();
parser.parse(reader, this, false);
where you defined an instance variable: MyParserDelegator parser;
You can now use parser.getCurrentLine() in any of you parser callback methods.
Note that you may not alway get the results that you expect for the current line as many times I found the line to be 1 greater than I thought it should be. Anyway you can decide if the code is of any value.
Following is the code for MyParserDelegator and MyDocumentmentParser inner class. Good Luck.
import java.io.IOException;
import java.io.Reader;
import java.io.Serializable;
import javax.swing.text.html.HTMLEditorKit;
import javax.swing.text.html.parser.DTD;
import javax.swing.text.html.parser.DocumentParser;
import javax.swing.text.html.parser.ParserDelegator;
public class MyParserDelegator extends ParserDelegator implements Serializable
{
MyDocumentParser parser;
public void parse(Reader r, HTMLEditorKit.ParserCallback cb, boolean ignoreCharSet) throws IOException
{
String name = "html32";
DTD dtd = createDTD( DTD.getDTD( name ), name );
parser = new MyDocumentParser(dtd);
parser.parse(r, cb, ignoreCharSet);
}
public int getCurrentLine()
{
return parser.getCurrentLine();
}
public class MyDocumentParser extends DocumentParser
{
public MyDocumentParser(DTD dtd)
{
super(dtd);
}
public int getCurrentLine()
{
return super.getCurrentLine();
}
}
}
Thanks for the code, but it did not give a good result: some start tags still have same line number but they are not on the same line.
in fact, I used in my own code a LineNumberReader instead of reader. this classe has the getLineNumber method, but, it generated similar result.
I tried to extend Reader to overwrite the read method, but I can not do it. When I create in my IDE (JBuilder6)the class myReader, it automatically generates the code:
--
import java.io.LineNumberReader;
public class myReader extends LineNumberReader {
public myReader() {
}
}
When I compile this piece of code, I get the error message: "constructor LineNumberReader() not found in class java.io.LineNumberReader at line 16, column 10"
I do not see why. Why?