• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

XML on the fly using servlets

 
Doshi Milan
Ranch Hand
Posts: 112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello friends,
I was programming using XML 1.0 and now I have shifted to Java API for XML Processing 1.1ea2.
I am trying to generate an XML document on the fly using servlet / JSP .
The pacakges imported by me are
import org.w3c.dom.*;
import javax.xml.parsers.*;
:
:// others
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance ();
DocumentBuilder db = dbf.newDocumentBuilder ();
Document doc = db.newDocument ();
::
::
ProcessingInstruction pi = doc.createProcessingInstruction("xml-stylesheet","type='text/xsl' href='/money.xsl' ");
doc.appendChild(pi) ;
::
::
Element root=(Element)doc.appendChild(doc.createElement("Account"));
::
and so on.
The probelem is how to send the document to the browser? What I mean is that I created the XmlDocument as above.In the earlier version (i.e XML ver 1.0) I used to write:
doc.write(out) ;// where out is the PrintWriter object.
But the same is not possible now. So what should I do ?
Also I would like to save the generated file .
Earlier I used to do:
doc.write(new FileOutputStream("storename.xml"));
The same is again not working here. Please advice the alternative.I would also appreciate if I can get some links from where I can get some ready examples and tutorials for Java API for XML Processing 1.1ea2. (espescially examples).
Thanks in advance,
Regards,
Milan Doshi


 
William Brogden
Author and all-around good cowpoke
Rancher
Posts: 13073
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here is the code I have used with JAXP 1.1 to write out a modified Document doc. The renameToBak method returns a valid File object.
//
public void writeXMLFile()
{
System.out.println( "writeXMLFile(). writing out xml file");
try{
File f = renameToBak();
TransformerFactory tfac = TransformerFactory.newInstance();
Transformer trans = tfac.newTransformer();
DOMSource source = new DOMSource( doc );
StreamResult result = new StreamResult( f );
trans.transform( source, result );
}
catch( TransformerException te ){
System.out.println("Transformer exception " + te );
}
catch (java.io.IOException ioe)
{
System.out.println( ioe.toString());
}
}
Bill
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic