Monday, November 16, 2009

Check Valid XML File Using Java

We can check the XML file is valid or not in different ways. If we are opening the XML file in Internet explorer or XML notepad then if we get some errors means the XML file invalid, so it might be because of unclosed tag or invalid characters.
     Here is the program checks the xml file is valid or not.
import java.io.File;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
public class CheckValidXML {
public static void main(String[] args) {


File xmlFile = new File("XML File Location");
if (xmlFile.exists()) {
if (isValidXMLFile(xmlFile.getAbsolutePath().toString())) {
System.out.println("Valid XML");
}
}
}
private static boolean isValidXMLFile(String filename) {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();


try {
File f = new File(filename);
if (f.exists()) {
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(f);
return true;
}


} catch (SAXParseException spe) {
System.out.println("Invalid XML");
return false;


} catch (SAXException sxe) {
System.out.println("Invalid XML");
return false;


} catch (ParserConfigurationException pce) {
System.out.println("Invalid XML");
return false;


} catch (IOException ioe) {
System.out.println("Invalid XML");
return false;
}
return true;
}
}


0 Comments:

Post a Comment

The Link Exchange - Your ultimate resource for link exchange!

About This Blog

  © Blogger template Webnolia by Ourblogtemplates.com 2009

Back to TOP