I am creating a tool that parses some files XML( XHTMLto be exact). The purpose of this tool is not only to check the XML structure, but also to check the value of some attributes.
So, I created my own org.xml.sax.helpers.DefaultHandlerfor event handling during XML parsing. One of my requirements is to have information about the current line number. So I decided to add org.xml.sax.helpers.LocatorImplto my DefaultHandler. This solves almost all my problems, except for one regarding XML attributes.
Take an example:
<rootNode>
<foo att1="val1"/>
<bar att2="val2"
answerToEverything="43"
att3="val3"/>
</rootNode>
One of my rules indicates that if an attribute is answerToEverythingdefined in node bar, its value should not differ from 42.
When you encounter such XML, my tool should detect an error. Since I want to give the exact error message to the user, for example:
Error in "foo.xhtml" file, line # 4: answerToEverything only allows the value "42".
My parser should be able to save the line number during parsing, even for attributes . If we consider the following implementation for my own class DefaultHandler:
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
System.out.println("Start element <" + qName + ">" + x());
for (int i = 0; i < attributes.getLength(); i++) {
System.out.println("Att '" + attributes.getQName(i) + "' = '" + attributes.getValue(i) + "' at " + locator.getLineNumber() + ":" + locator.getColumnNumber());
}
}
then for node >bar>it will display the following output:
Starting element at 5:23
Att 'att2' = 'val2' at 5:23
Att 'answerToEverything' = '43' at 5:23
Att 'att3' = 'val3' at 5:23
, , node, .
, ContentHandler startAttribute startElementBeforeReadingAttributes, : o)
, : ?
, Java 6
ps: , Java SAX , , - ...