XML Error checker and locater (DOM)

In this section, you will learn to check and locate
(line and column number) an error in your XML document using the DOM
APIs. The XML document follows some rules to check its syntax.
Description of program:
This program takes a XML file on the console and
it checks whether the given file exists or not. If it exists then it parses the
file using the parse()
method. DocumentBuilderFactory
and DocumentBuilder classes are needed to get a dom parser. All
the parsers have inbuilt capability to verify the well-formed ness of a
xml file . No you need not to add any extra method for checking wellformed ness
.If the xml file is wellformed , the parsing of the xml document get
successfully completed , and the program displays a message like "Employee-Detail.xml
is well-formed!". Otherwise, it displays an error and exact error
location (line and column number).
Here is the XML File: Employee-Detail1.xml
<?xml version = "1.0" ?>
<Employee-Detail>
<Employee>
<Emp_Id> E-001 </Emp_Id>
<Emp_Name> Vinod </Emp_Name>
<Emp_E-mail> Vinod1@yahoo.com </Emp_E-mail>
</Employee
</Employee-Detail> |
Here is the Java File: DOMLocateError.java
import java.io.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import org.xml.sax.*;
public class DOMLocateError{
static public void main(String[] arg){
try {
BufferedReader bf = new BufferedReader(new
InputStreamReader(System.in));
System.out.print("Enter File name: ");
String xmlFile = bf.readLine();
File file = new File(xmlFile);
if(file.exists()){
// Create a new factory
DocumentBuilderFactory factory =
DocumentBuilderFactory.newInstance();
// Use the factory to create builder document.
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(xmlFile);
System.out.println(xmlFile + " is well-formed!");
}
else{
System.out.print("File not found!");
}
}
catch (SAXParseException e) {
System.out.println("type" + ": " + e.getMessage()+"\n");
System.out.println("Line " + e.getLineNumber() + " Column "
+ e.getColumnNumber());
}
catch (SAXException e) {
System.err.println(e);
System.exit(1);
}
catch (ParserConfigurationException e) {
System.err.println(e);
System.exit(1);
}
catch (IOException e) {
System.err.println(e);
System.exit(1);
}
}
}
|
Download this example.
Output of this program:
C:\vinod\xml>javac DOMLocateError.java
C:\vinod\xml>java DOMLocateError
Enter File name: Employee-Detail1.xml
[Fatal Error] Employee-Detail1.xml:9:1: The end-tag for element type "Employee"
must end with a '>' delimiter.
type: The end-tag for element type "Employee" must end with a '>' delimiter.
Line 9 Column 1 |

|
Current Comments
0 comments so far (post your own) View All Comments Latest 10 Comments: