Following code parses xml files under a directory. (It was recursive one.)
We have a web application which is very much similar to struts framework.
So we have tons of xml preference files.
Before launching tomcat, I will invoke the following code to make sure that
all xml files were valid one.
public void parseDirectory(String fullpath)
{
if ( fullpath == null) return;
Path path = new Path(fullpath);
File file = path.toFile();
File[] files = file.listFiles();
if (files==null) return;
int size = files.length;
for (int i=0; i .lt. size; i=i+1)
{
if (files[i].isDirectory())
{
File[] dirFiles = files[i].listFiles();
String dirName =files[i].getName();
System.out.println("\n processing directory"+dirName);
for (int j=0; j .lt. dirFiles.length; j=j+1)
{
File subDirFile = dirFiles[j];
String subDirFileName = subDirFile.getName();
if ( subDirFileName.endsWith(".xml"))
{
parseXmlile(files[i].getName();
}
else
{
if ( subDirFile.isDirectory() ) parseDirectory(subDirFileName);
}
}
}
else
{
String fileName = files[i].getName();
if ( fileName.endsWith(".xml"))
{
parseXmlile(files[i].getName();
}
else
{
// it is not a xml file & directory.. so skip it.
}
}
}
}
public void parseXmlile(String fileName)
{
try
{
System.err.println("Parsing " + fileName + "...");
// Make the document a URL so relative DTD works.
String uri = "file:" + new File(fileName).getAbsolutePath();
XmlDocument doc = XmlDocument.createXmlDocument(uri);
System.out.println("Parsed OK...");
}
catch (SAXParseException ex)
{
System.err.println("================================");
System.err.println("| *Parse Error* |");
System.err.println("================================");
System.err.println("+ Line " + ex.getLineNumber ()
+ ", uri " + ex.getSystemId ());
System.err.println(ex.getClass());
System.err.println(ex.getMessage());
System.err.println("================================");
}
catch(SAXException ex)
{
System.err.println("================================");
System.err.println("| *SAX XML Error* |");
System.err.println("================================");
System.err.println(ex.toString());
}
catch (IOException ex)
{
System.err.println("================================");
System.err.println("| *Input/Output Error* |");
System.err.println("================================");
System.err.println(ex.toString());
}
catch (Exception ex)
{
System.err.println("================================");
System.err.println("| Unknown error |");
System.err.println("================================");
System.err.println(ex.toString());
}
}
No comments:
Post a Comment