Sunday, July 15, 2007

Reading xml from WEB-INF Directory and Building XML Document

We had a requirement of reading a xml file from the WEB-INF folder of web-app
and to build a xml document from the file, after building the document its very much easy to
parse through the document and get the date.Here are the steps and code-snippets to do it.

Since its a web-app we need to get the ServletContext.


ServletContext context = pageContext.getServletContext();



After getting the context we need get the file as Stream for building xml document


InputStream inputStream=context.getResourceAsStream("/WEB-INF/example.xml");



We have got the inputStream we need a build the xml document.The below DomRead.java
will build the document


Document document = DomReadUtil.parse(inputStream);




public class DomRead
{
public static Document parse(InputStream stream )
{
Document document = null;
// Initiate DocumentBuilderFactory
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
// To get a validating parser
factory.setValidating(false);
// To get one that understands namespaces
factory.setNamespaceAware(true);
try
{
// Get DocumentBuilder
DocumentBuilder builder = factory.newDocumentBuilder();
// Parse and load into memory the Document
document = builder.parse(stream);
return document;
}
catch (SAXParseException spe)
{
// Error generated by the parser
System.out.println("\n** Parsing error , line " + spe.getLineNumber()
+ ", uri " + spe.getSystemId());
System.out.println(" " + spe.getMessage() );
// Use the contained exception, if any
Exception x = spe;
if (spe.getException() != null)
x = spe.getException();
x.printStackTrace();
}
catch (SAXException sxe)
{
// Error generated during parsing
Exception x = sxe;
if (sxe.getException() != null)
x = sxe.getException();
x.printStackTrace();
}
catch (ParserConfigurationException pce)
{
// Parser with specified options can't be built
pce.printStackTrace();
} catch (IOException ioe) {
// I/O error
ioe.printStackTrace();
}
return null;
}
}



Now we got the XMLDocument document we can parse the xml document and get the
information we need.

Note :

The inputStream passing to the DomRead.java should be opened or Read, if so it will give
Premature End Of File - SaxParseException.


ServletContext context = pageContext.getServletContext();
InputStream inputStream=context.getResourceAsStream("/WEB-INF/example.xml");
StringBuffer sb=new StringBuffer();
BufferedReader br=new BufferedReader(new InputStreamReader(inputStream));
while(br.readLine()!=null)
{
sb.append(br.readLine()+"\n");
}
System.out.println("fpath "+sb.toString());
Document document = DomReadUtil.parse(inputStream);



The above code will give you Premature End Of File - SaxParseException.Because we have opened the inputStream and Read the contents.when trying to build the Doc from the stream,its already read.so there is premature end of file

0 comments: