I wrote a quick xml file that receives line numbers and throws an exception in case of an unwanted attribute and gives the text in which the error was thrown.
import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Stack; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.apache.log4j.Logger; import org.w3c.dom.Document; import org.xml.sax.Attributes; import org.xml.sax.Locator; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; public class LocatorTestSAXReader { private static final Logger logger = Logger.getLogger(LocatorTestSAXReader.class); private static final String XML_FILE_PATH = "lib/xml/test-instance1.xml"; public Document readXMLFile(){ Document doc = null; SAXParser parser = null; SAXParserFactory saxFactory = SAXParserFactory.newInstance(); try { parser = saxFactory.newSAXParser(); DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); doc = docBuilder.newDocument(); } catch (ParserConfigurationException e) {
in relation to text, depending on where the error occurs in the xml file, there can be no text. So with this xml:
<?xml version="1.0"?> <root> <section> <para>This is a quick doc to test the ability to get line numbers via the Locator object. </para> </section> <section bad:attr="ok"> <para>another para.</para> </section> </root>
if bad attr is in the first element, the text will be empty. In this case, the exception was:
org.xml.sax.SAXException: found attr : bad:attr=ok that starts with bad! at line : 6 at element section element occurs below text : This is a quick doc to test the ability to get line numbers via the Locator object.
When you say you tried to use the Locator object, what exactly was the problem?
source share